|
Home > Archive > Unix Programming > April 2005 > Mixing C and C++ code
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Mixing C and C++ code
|
|
| Ramon F Herrera 2005-03-14, 7:57 am |
| This is the first time that I try to link code written in
C with C++ code.
I have a program whose source is called 'server.c' which should make
a call to a function inside another source code called 'works.cc'.
The 2 compilations work fine, but when I try to perform the link
I get a this error message:
gcc works.o server.o -o server -lstdc++ -lm
server.o(.text+0x3df): In function `main':
: undefined reference to `somefunction'
collect2: ld returned 1 exit status
make: *** [server] Error 1
The problem is trivially fixed by just renaming the source
from 'server.c' to 'server.cc', but I still would like to know
what I am doing wrong.
What is the correct procedure to make calls from one language
to the other??
TIA,
-Ramon F Herrera
| |
|
|
| BlueOwl 2005-04-14, 6:03 pm |
| If you use .cc suffix the code is supposed to be a C++ and that's why C++
compiler (actually g++) is used. So it result in that both your files are
compiled by C++ compiler.
The problem with mixing of C code (compiled with C compiler) and C++ code
(compiled with C++ compiler) is in that, C++ compiler changes functions
names. It is called mangling. So the function name is not the same in
object files produced by C and C++ compiler.
To handle this issue, you have to use extern "C" { C function
declaration }
in your C++ code, so that C++ compiler knows you call C function and didn't
mangle the function name.
Jirka
Ramon F Herrera wrote:
> This is the first time that I try to link code written in
> C with C++ code.
>
> I have a program whose source is called 'server.c' which should make
> a call to a function inside another source code called 'works.cc'.
>
> The 2 compilations work fine, but when I try to perform the link
> I get a this error message:
>
> gcc works.o server.o -o server -lstdc++ -lm
> server.o(.text+0x3df): In function `main':
> : undefined reference to `somefunction'
> collect2: ld returned 1 exit status
> make: *** [server] Error 1
>
> The problem is trivially fixed by just renaming the source
> from 'server.c' to 'server.cc', but I still would like to know
> what I am doing wrong.
>
> What is the correct procedure to make calls from one language
> to the other??
>
> TIA,
>
> -Ramon F Herrera
|
|
|
|
|