C code compiled with C++: undefined reference
Asked Answered
W

4

13

I have a small program that I can compile with GCC and ICC without any difficulties, but I would also like the code to work with G++ and ICPC. I tried to add this:

#ifdef __cplusplus
  extern "C" {
#endif

at the beginning and this:

#ifdef __cplusplus
  }
#endif

at the end of all the header files, but I still get several `undefined reference to "..."' errors.

Whisenhunt answered 13/5, 2010 at 13:53 Comment(3)
First thought: is __cplusplus defined?Adroit
yes, it's defined by C++ compilers (or at least, those I use)Whisenhunt
possible duplicate of Newbie question: When to use extern "C" { //code } ?Climax
T
11

I think you're getting it wrong... The extern C is for disabling the function mangling; so if you do it just for the header files, when you try to link your mangled object code, the declared function names won't match with the function names in the object file.

Anyway, the extern C won't add any portability if the whole application is being compiled and linked with the same C++ compiler, it's intended for mixing C libraries with C++ code.

If your code is in the common subset of C and C++, you should be already able to compile it with either compiler, but I cannot see the reason to do that (besides working on the principle of least surprise, as C++ is more strict with some things).

Thither answered 13/5, 2010 at 14:1 Comment(0)
F
2

You get undefined references because the declaration and the definition are not matching if you put extern "C", which prevents name mangling from happening: but in this case this is happening only in your header files.

Factory answered 13/5, 2010 at 14:2 Comment(0)
S
1

If one of the undefined references is gxx_personality, then I'd say the post by "fortran" is correct.

Sigma answered 13/5, 2010 at 14:6 Comment(1)
Nothing about gxx_personality, I only get undefined references for two fairly simple functions. One of the "undefined function" is in file "a.h/a.c" and can be used correcly in these files, but for some reason doesn't work in file "b.c".Whisenhunt
C
1

See my response to this earlier question: When to use extern "C" in simple words?

It should hopefully make it clear how to mix C and C++ code.

Climax answered 13/5, 2010 at 14:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.