[英]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
我想尝试在 C++ 文件中使用 C 代码。 出于同样的原因,我在 test.h 中声明了一个 function 并在 test.c 中定义并在 main.cpp 中使用它
main_temp.c 仅用于说明。
测试.h
void test(int);
测试.c
#include <stdio.h>
void test(int a) {
printf("%d", a);
main_temp.cpp
#include "test.h"
int main() {
foo(5);
}
在这里,我明白为什么这不起作用。 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. 所以,我会使用 extern "C" 并且我的 main.cpp 变成这样:
主文件
extern "C" {
#include "test.h"
}
int main() {
foo(5);
}
我不明白为什么这不起作用:我得到:
main.cpp:(.text+0xa): undefined reference to `test`
有人可以分享见解吗?
我相信您将它们编译或链接在一起? 否则那将是原因。 在 gcc 上,它将类似于:
g++ -c -o main.o main.cpp
gcc -c -o test.o test.c
g++ -o a.out main.o test.o
假设您没有编译/链接错误,请将 main.cpp 和 test.c 编译成 object 文件并在两者上运行nm
。 它将显示main.o
想要什么符号以及test.o
导出什么符号。 那么应该清楚为什么 linker 不能完成它的工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.