将C编译的静态库链接到C++程序

Pra*_*abu 16 c c++ linux gcc g++

我试图将一个静态库(用gcc编译)链接到一个c ++程序,我得到了'未定义的引用'.我在ubuntu 12.04服务器机器上使用了gcc和g ++版本4.6.3.例如,以下是factorial方法的简单库文件:

mylib.h

#ifndef __MYLIB_H_
#define __MYLIB_H_

int factorial(int n);

#endif
Run Code Online (Sandbox Code Playgroud)

mylib.c

#include "mylib.h"

int factorial(int n)
{
    return ((n>=1)?(n*factorial(n-1)):1);
}
Run Code Online (Sandbox Code Playgroud)

我使用gcc为这个mylib.c创建了对象:

gcc -o mylib.o -c mylib.c
Run Code Online (Sandbox Code Playgroud)

同样,静态库是使用AR实用程序从目标文件创建的:

ar -cvq libfact.a mylib.o
Run Code Online (Sandbox Code Playgroud)

我用C程序(test.c)和C++程序(test.cpp)测试了这个库

C和C++程序都有相同的主体:

#include "mylib.h"
int main()
{
    int fact = factorial(5);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

假设在/ home/test目录中有静态库libfact.a,我编译了我的C程序没有任何问题:

gcc test.c -L/home/test -lfact
Run Code Online (Sandbox Code Playgroud)

但是在测试C++程序时,它引发了一个链接错误:

g++ test.cpp -L/home/test -lfact

test.cpp:(.text+0x2f): undefined reference to `factorial(int)'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

我甚至尝试在test.cpp中添加extern命令:

extern int factorial(int n) //added just before the main () function
Run Code Online (Sandbox Code Playgroud)

还是一样的错误.

  • 谁能告诉我这里错了什么?
  • 创建静态库时有什么我错过的吗?
  • 我是否必须添加任何内容test.cpp才能使其正常工作?

joh*_*ohn 23

问题是你没有告诉你的C++程序,因子是用C语言编写的.你需要更改你的test.h头文件.像这样

#ifndef __MYLIB_H_
#define __MYLIB_H_

#ifdef __cplusplus
extern "C" {
#endif

int factorial(int n);

#ifdef __cplusplus
}
#endif

#endif
Run Code Online (Sandbox Code Playgroud)

现在你的头文件应该适用于C和C++程序.详情请见此处.

包含双下划线的BTW名称保留给compliler(名称以下划线和大写字母开头),因此#ifndef __MYLIB_H_严格来说是非法的.我会改为#ifndef MYLIB_H #define MYLIB_H

  • 是的,它的魅力就像这样.谢谢你的链接.感谢您添加有关双下划线的信息. (3认同)