How do you use extern "C" to call C++ functions in C
g++, gcc
Solution
You can compile your C code with gcc and make use of those C++ functions, but you have to link the final executable with g++, because the C++ functions need the C++ standard library:
g++ printSrcOO.o printMain.o -o myProgram
Alternatively, you can try to manually link against the C++ library with gcc:
gcc printSrcOO.o printMain.o -o myProgram -lstdc++
But I'd stick to linking with g++ since I'm not sure whether it sets other important link flags.
Problem
So I've read about a dozen pages explaining how to do this, and for the life of me I can't get it to work. I have a library written in C++, and a set of code written in C that is compiled with the gnu compiler, and I just can't seem to be able to call the C++ code from C. I have a library written in C++: printHeadOO.hpp ``` #ifdef __cplusplus extern "C" #endif void printThis(void); ``` printSrcOO.cpp ``` #include "printHeadOO.hpp" #include <iostream> void printThis(void){ std::cout<<"This is Printed Using C++ \n"; } ``` okay cool, if I call this from a C++ program , it compile, runs and everything is happy. But suppose instead I call it from a C program: printMain.c ``` #include <stdio.h> #include "printHeadOO.hpp" int main(void){ printf("This is printed from C Main \n"); printThis(); return 0; } ``` so everything compiles just fine with: ``` #g++ -c printSrcOO.cpp #gcc -c printMain.c ``` but then at link-time: ``` #gcc printSrcOO.o printMain.o -o myProgram ``` gcc yaks up the following: ``` printSrcOO.o: In function `__static_initialization_and_destruction_0(int, int)': printSrcOO.cpp:(.text+0x23): undefined reference to `std::ios_base::Init::Init()' printSrcOO.o: In function `__tcf_0': printSrcOO.cpp:(.text+0x6c): undefined reference to `std::ios_base::Init::~Init()' printSrcOO.o: In function `printThis': printSrcOO.cpp:(.text+0x83): undefined reference to `std::cout' printSrcOO.cpp:(.text+0x88): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)' printSrcOO.o:(.eh_frame+0x11): undefined reference to `__gxx_personality_v0' collect2: ld returned 1 exit status ``` How do I get g++ to create hooks that gcc will use? Am I just doing something stupid/missing something? TIA Dan