简体   繁体   中英

Calling C code from C++ with using extern “C”

I have 3 files with me, one c++ file, main.cpp, one c file, test.c and one header file, test.h

I wanted to try and use C code into C++ file. For the same reason, I have declared an function in test.h and defined that in test.c and using that in main.cpp

main_temp.c is just for explanation.

test.h

void test(int);

test.c

#include <stdio.h>
void test(int a) {
  printf("%d", a);

main_temp.cpp

#include "test.h"
int main() {
  foo(5);
}

Here, I understand why this would not work. C symbol would be simple 'foo' but since C++ does more things while creating symbols, it might be 'void@test(int)' and to solve this name mangling problem, I have to treat C++ symbol as a C symbol. So, I would use extern "C" and my main.cpp becomes as like:

main.cpp

extern "C" {
  #include "test.h"
}
int main() {
  foo(5);
}

I could not understand as to why this would not work: I get :

main.cpp:(.text+0xa): undefined reference to `test`

Can somebody share the insights?

I trust you compile or link them together? Else that would be the cause. On gcc it would be something like:

g++ -c -o main.o main.cpp
gcc -c -o test.o test.c
g++ -o a.out main.o test.o

Assuming you have no bugs with compiling/linking, compile both main.cpp and test.c into object files and run nm on both. It will show what symbol main.o wants and what symbol test.o exports. It should become clear then why linker cannot do its job.

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