简体   繁体   English

使用外部“C”从 C++ 调用 C 代码

[英]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 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.我想尝试在 C++ 文件中使用 C 代码。 For the same reason, I have declared an function in test.h and defined that in test.c and using that in main.cpp出于同样的原因,我在 test.h 中声明了一个 function 并在 test.c 中定义并在 main.cpp 中使用它

main_temp.c is just for explanation. main_temp.c 仅用于说明。

test.h测试.h

void test(int);

test.c测试.c

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

main_temp.cpp 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. 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:所以,我会使用 extern "C" 并且我的 main.cpp 变成这样:

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:在 gcc 上,它将类似于:

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.假设您没有编译/链接错误,请将 main.cpp 和 test.c 编译成 object 文件并在两者上运行nm It will show what symbol main.o wants and what symbol test.o exports.它将显示main.o想要什么符号以及test.o导出什么符号。 It should become clear then why linker cannot do its job.那么应该清楚为什么 linker 不能完成它的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM