未定义的gcc函数引用

时间:2014-06-30 14:08:38

标签: c++ c

我正在尝试使用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

2 个答案:

答案 0 :(得分:2)

只有在声明/定义函数时才指定函数参数类型,而不是在调用函数时。函数调用应该看起来像

print_cplusplus(a);

您还需要在testcplusplus.h中加入test.c,以便在您调用时声明可用。 main的返回类型必须为int;并且print_cplusplus应该有void返回类型,或者应该返回一个值。

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

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

void print_cplusplus(int b);

#ifdef __cplusplus
}
#endif

答案 1 :(得分:0)

使用它时,你不会重写变量类型,它只在声明中使用:

print_cplusplus(a);