In order to resolve this, one has to understand how are C and C++ languages compiled. I will not attempt to explain it here, others have already done much better job that I can. So, I will just mention the relevant parts.
There is nothing special about C or C++ headers, #include
literally just pastes the file contents (recursively).
Every translation unit (~ one .c{pp} file and all included headers) is compiled separately into an object file containing symbol tables and (almost) compiled code.
What is likely causing the issue is either C or C++ specific code in header files (neither language is a superset of the other) or C++ symbol mangling - as pointed out by @pmg. There is not much that can be done with the former. The latter can solved using extern "C"
foo.h
void foo(void);
foo.c
#include "foo.h"
#include <stdio.h>
void foo(void){
printf("Hello from C\n");
}
Running gcc -c foo.c
will create foo.o
that contains the implementation for the function symbol foo
.
main.cpp
extern "C"{
#include "foo.h"
}
int main(){
foo();
}
Similarly, g++ -c main.cpp
will create main.o
object file.
Then, running g++ -o program.out main.o foo.o
will link them together into program.out
executable.
> ./program.out
Hello from C
extern "C"{}
disables symbol mangling and because the included code is just pasted there, it is applied to the whole file. So, main.o
function symbol table says that it seeks foo
function symbol instead of _Z3foov
or something similar.