gpt4 book ai didi

c++ - gcc 中对函数的 undefined reference

转载 作者:行者123 更新时间:2023-11-30 20:14:47 27 4
gpt4 key购买 nike

我尝试使用 C 静态库,但在 gcc 中编译/链接时出现以下错误。主文件test.c需要调用静态库libtest.a中的函数

头文件:testcplusplus.h

void print_cplusplus(int b);

testcplusplus.c:

#include <stdio.h>
#include "testcplusplus.h"
void print_cplusplus(int b) {
printf ("Value of b is %d \n",b);
}

主C文件:test.c

 #include <stdio.h>
#include "testcplusplus.h"
int main() {
int a = 2 ;
print_cplusplus(a);
}

使用的命令:

g++ -c -o testcplusplus.o testcplusplus.c
ar rvs libtest.a testcplusplus.o
gcc -o test test.c -L. -ltest **// Error comes here**

错误:

    In function `main':
test.c:(.text+0x15): undefined reference to `print_cplusplus'
collect2: ld returned 1 exit status

最佳答案

仅在声明/定义函数时指定函数参数类型,而不是在调用函数时指定。函数调用应该类似于

print_cplusplus(a);

您还需要包含 test.c 中的 testcplusplus.h,以便在调用它时声明可用。 main的返回类型需要为int;和 print_cplusplus 应该具有 void 返回类型,或者应该返回一个值。

最后,您需要声明函数 extern "C",以便可以从 C 程序调用它 - 但仅限于编译 C++ 时。

// testcplusplus.h
#ifdef __cplusplus
extern "C" {
#endif

void print_cplusplus(int b);

#ifdef __cplusplus
}
#endif

关于c++ - gcc 中对函数的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24492049/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com