Using C code from C++ code causes linker error -- and how to fix it
Recently, I came across a non-trivial linker error where GCC complained that “ld failed with exit code 1.″ It had very little information other than where the issue was. This was in some C++ code I had written which was trying to use a new function I had written. The new function was part of a C library.
Weirdly, the new C files I added were linking correctly in another project. The only noticeable difference between the two cases was that the other project was completely in C, while the project with the error was in C++.
The learning here is that just because C++ compilers compile C, doesn’t mean that you can call into any function written in the other language for free. In my case, I had to declare the function I was trying to use from C in my C++ code with:
extern “C”
So that means I added this at the top of my C++ file:
extern “C” my_c_function(void* arg1, void* arg2);
You can also enclose the headers in {} instead of starting each header line with extern “C”:
extern “C” {
my_c_function_1( void* arg1, void* arg2);
my_c_function_2( void* arg1, void* arg2);
}
Reading up more about using C++ code in C and vice versa, it made sense that you shouldn’t be able to use C++ directly in C, because C++ can have classes and member functions that C cannot. For that case, you have to write some intermediary code so that your C can call into the C++.










