I'm writing my thesis and I have problem with using C++ function in C code. I searched solution and I found a lot of them, but it didn't work anyway. Please explain it to me one more time.
To be quick I have something like below and after gcc main.c -o main
I get undefined reference to 'cppfun'
cpp.h:
#pragma once
#ifdef __cplusplus
extern "C" {
#endi
void cppfun();
#ifdef __cplusplus
}
#endif
cpp.cpp:
#include <stdio.h>
#include "cpp.h"
void cppfun()
{
printf("cpp_fun");
}
main.c:
#include <stdio.h>
#indlude "cpp.h"
int main(int argc, char *argv[])
{
cppfun();
return 0;
}
When you combine C and C++, you should compile the translation unit containing the main
function, as C++. Not opposite. This is a FAQ.
An undefined reference is usually because you haven't linked in the translation unit where the missing thing is. Your stated build command is
gcc main.c -o main
while it should be e.g.
gcc -c main.c
g++ -c cpp.cpp
g++ cpp.o main.o -o main
except as mentioned, the main translation unit should be in C++.