我试图将静态库(与gcc一起编译)链接到C++程序,但出现了“ undefined reference ”。我在ubuntu 12.04服务器计算机上使用了gcc和g++版本4.6.3。例如,这是阶乘方法的简单库文件:
mylib.h
#ifndef __MYLIB_H_
#define __MYLIB_H_
int factorial(int n);
#endif
mylib.c
#include "mylib.h"
int factorial(int n)
{
return ((n>=1)?(n*factorial(n-1)):1);
}
我使用gcc为此mylib.c创建了对象:
gcc -o mylib.o -c mylib.c
再次使用AR实用工具从目标文件创建了静态库:
ar -cvq libfact.a mylib.o
我用C程序(test.c)和C++程序(test.cpp)测试了这个库
C和C++程序具有相同的主体:
#include "mylib.h"
int main()
{
int fact = factorial(5);
return 0;
}
假定静态库libfact.a在/home/test目录中可用,我编译了C程序,没有任何问题:
gcc test.c -L/home/test -lfact
但是,在测试C++程序时,它引发了链接错误:
g++ test.cpp -L/home/test -lfact
test.cpp:(.text+0x2f): undefined reference to `factorial(int)'
collect2: ld returned 1 exit status
我什至尝试在test.cpp中添加extern命令:
extern int factorial(int n) //added just before the main () function
还是一样的错误。
test.cpp
中添加任何内容才能使其正常工作? 最佳答案
问题是您没有告诉C++程序阶乘是用C编写的。您需要更改test.h头文件。像这样
#ifndef __MYLIB_H_
#define __MYLIB_H_
#ifdef __cplusplus
extern "C" {
#endif
int factorial(int n);
#ifdef __cplusplus
}
#endif
#endif
现在,您的头文件应该对C和C++程序都适用。有关详细信息,请参见here。
包含双下划线的BTW名称保留给编译器使用(以下划线和大写字母开头的名称),因此严格来讲
#ifndef __MYLIB_H_
是非法的。我将更改为#ifndef MYLIB_H #define MYLIB_H