Call C++ function from C

T

tathanhdinh

Dear all
I have a problem with calling C++ function from C. I have two seperate
library, one in C and other in C++. The C project could only compile
with C compiler (gcc) (When I compile with g++, the result is tons of
errors). But now I have to call some function of C++ library from C
library.
Example:
// In C++ library
foo() { /* ... */ }

// In C project
bar() { foo(); }

As far as I know, create header for foo (in C++ library):
// foo.h
extern "C" foo();
// ...

Include foo.h in C library and the problem is: I must compile C library
in gcc and link to C++, but the compiler doesn't work.
Please give me some ideas. Thanks.
 
I

Ian Collins

tathanhdinh said:
Dear all
I have a problem with calling C++ function from C. I have two seperate
library, one in C and other in C++. The C project could only compile
with C compiler (gcc) (When I compile with g++, the result is tons of
errors). But now I have to call some function of C++ library from C
library.
Example:
// In C++ library
foo() { /* ... */ }

// In C project
bar() { foo(); }

As far as I know, create header for foo (in C++ library):
// foo.h
extern "C" foo();
// ...
Use conditional wrappers:

#ifdef __cplusplus
extern "C" {
#endif

void foo();

#ifdef __cplusplus
}
#endif
Include foo.h in C library and the problem is: I must compile C library
in gcc and link to C++, but the compiler doesn't work.

The compiler works fine, the problem's with your code!
 
P

Philip Potter

Ian Collins said:
Use conditional wrappers:

#ifdef __cplusplus
extern "C" {
#endif

void foo();

#ifdef __cplusplus
}
#endif

In code which may be compiled as C, void foo(void); is better style, since
void foo(); doesn't specify parameter types in C.

Philip
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top