简体   繁体   中英

Mixing C++ code with C code in a library produces undefined symbol errors

I have a library that consists of some.c modules and some.cpp modules. I assume that's fine when the library is linked into a C++ main program. But when I attempt to link that library into a C program, I get linker errors for 'standard C++ library' modules.

gcc -o PSEQ.app -Xlinker --allow-shlib-undefined pseq.app.o -L../librep -lrep

..librep/ssuinventbean.cpp:62: undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string()'

The program in question is not written in C++ - and it does not reference the ssuinventbean.cpp module. I asked a similar question about unreferenced shared library modules complaining about stuff called from there, and was told that the --allow-shlib-undefined linker flag could be used to get around that. I tried using that flag in the gcc command above, but obviously it doesn't work as advertised when the library in question is a statically linked library.

Normally, that wouldn't be a problem. I can make sure that all the modules in my application libraries have all of their references satisfied. But in this case, the reference is to the standard C++ library, which I assume would've been included if the main module of the program in question were in C++. So, catch-22? Can I not have C++ code in a library if that library will be linked against a non-C++ app - even if the.cpp module in question is never referenced? Do I have to segregate all C++ library code into its own.a files to be included only when building apps that call that code?

I found out what was causing this. It turned out that somebody had put a variable definition into ah file that was pulled into this.cpp file. I guess it's undefined what the compiler will do with a global variable in ah file (it could end up getting defined in multiple.c or.cpp files that pull it in).

Anyway the.cpp file in question apparently pulled in that.h file as extern "C" code, which caused something else to pull in the.cpp module (presumably to pick up the global variable). After I commented out the global variable in the.h file, the app was able to build with gcc instead of g++ on the linker line in my makefile. Problem solved.

It turns out that the link maps generated in linux by these flags are very useful. Told me that the global variable was what caused the otherwise unreferenced.cpp module to be included...

MAPFLAGS = -Xlinker --cref -Xlinker -Map=MAP

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM