将 C 编译的静态库链接到 C++ 程序 [英] Linking C compiled static library to C++ Program
问题描述
我试图将一个静态库(用 gcc 编译)链接到一个 c++ 程序,但我得到了未定义的引用".我在 ubuntu 12.04 服务器机器上使用了 gcc 和 g++ 版本 4.6.3.例如,下面是阶乘法的简单库文件:
I tried to link a static library (compiled with gcc) to a c++ program and I got 'undefined reference'. I used gcc and g++ version 4.6.3 on a ubuntu 12.04 server machine. For example, here is the simple library file for factorial method:
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 创建了对象:
I created object for this mylib.c using gcc:
gcc -o mylib.o -c mylib.c
再次使用 AR 实用程序从目标文件创建静态库:
Again the static library was created from the object file using AR utility:
ar -cvq libfact.a mylib.o
我用 C 程序 (test.c) 和 C++ 程序 (test.cpp) 测试了这个库
I tested this library with a C program (test.c) and C++ program (test.cpp)
C 和 C++ 程序具有相同的主体:
Both C and C++ program have the same body:
#include "mylib.h"
int main()
{
int fact = factorial(5);
return 0;
}
假设静态库 libfact.a 在/home/test 目录中可用,我编译我的 C 程序没有任何问题:
Assuming static library libfact.a is available in /home/test directory, I compiled my C program without any issues:
gcc test.c -L/home/test -lfact
但是在测试 C++ 程序时,它抛出了一个链接错误:
However while testing C++ program, it threw a link error:
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 命令:
I even tried adding extern command in test.cpp:
extern int factorial(int n) //added just before the main () function
还是同样的错误.
- 谁能告诉我这里哪里错了?
- 我在创建静态库时有什么遗漏吗?
- 我是否必须在我的
test.cpp
中添加任何内容才能使其正常工作?
- Can someone tell me what I am wrong here?
- Is there anything I missed while creating the static library?
- Do I have to add anything in my
test.cpp
to make it work?
推荐答案
问题是你没有告诉你的C++程序阶乘是用C写的.你需要改变你的test.h头文件.像这样
The problem is that you haven't told your C++ program that factorial is written in C. You need to change your test.h header file. Like this
#ifndef __MYLIB_H_
#define __MYLIB_H_
#ifdef __cplusplus
extern "C" {
#endif
int factorial(int n);
#ifdef __cplusplus
}
#endif
#endif
现在您的头文件应该适用于 C 和 C++ 程序.有关详细信息,请参阅此处.
Now your header file should work for both C and C++ programs. See here for details.
包含双下划线的 BTW 名称是为编译器保留的(以下划线和大写字母开头的名称也是如此),因此严格来说 #ifndef __MYLIB_H_
是非法的.我会改为 #ifndef MYLIB_H #define MYLIB_H
BTW names containing a double underscore are reserved for the compliler (so are names starting with an underscore and a capital letter) so #ifndef __MYLIB_H_
is illegal strictly speaking. I would change to #ifndef MYLIB_H #define MYLIB_H
这篇关于将 C 编译的静态库链接到 C++ 程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!