使用C库不链接的gcc / g ++的 [英] C-library not linking using gcc/g++

查看:121
本文介绍了使用C库不链接的gcc / g ++的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C库我在gcc时使用。图书馆有扩展的.lib,但总是连在一起作为静态库。如果我写它使用库作为C- code,一切,都OK的程序。如果我不过文件重命名为.CPP(做简单的东西,在这两个C / C ++工程)我得到了一个未定义的参考。这些都是简单的小程序我写的用于测试目的所以没有花哨的东西。我编译使用:

I have a c-library which I use in gcc. The library has the extension .lib but is always linked as a static library. If i write a program which uses the library as c-code, everything as a-ok. If I however rename the file to .cpp (doing simple stuff that works in both c/c++) I get undefined reference. These are simple small programs I write for testing purposes so no fancy stuff. I compile using:

gcc -g -Wall -I <path to custom headers> -o program main.c customlibrary.lib -lm -lpthread

以上的作品就像一个魅力。但是:

The above works like a charm. However:

g++ -g -Wall -I <path to custom headers> -o program main.cpp customlibrary.lib -lm -lpthread

gcc -g -Wall -I <path to custom headers> -o program main.cpp customlibrary.lib -lm -lpthread -lstdc++

结果不确定的参考customlibrary.lib任何功能。我试图创建符号链接名为customlibrary.a但没有运气。

results in undefined reference to any function in customlibrary.lib. I tried creating a symbolic link named customlibrary.a but no luck.

任何想法将大大appriciated。为什么不会g ++的发现识别我的图书馆。不幸的是我没有访问库的源$ C ​​$ C,但链接一个C-lib添加到C ++应该不会有问题吧?

Any ideas would be much appriciated. Why won't g++ find recognize my library. Unfortunately I have no access to the source code of the libraries but linking a c-lib to c++ should not be a problem right?

推荐答案

您库中似乎有假定它会从C,而不是C ++调用的API。这是重要的,因为C ++有效地需要从库导出的符号,在他们不仅仅是函数名的更多信息。这是由名称重整的功能来处理。

Your library appears to have an API that assumes it will be called from C, not C++. This is important because C++ effectively requires that the symbols exported from a library have more information in them than just the function name. This is handled by "name mangling" the functions.

我假设你的库有一个声明公共接口包含文件。为了使其与C和C ++兼容,您应该安排告诉C ++编译器,它声明的职能应假定用C的联动和命名。

I assume your library has an include file that declares its public interface. To make it compatible with both C and C++, you should arrange to tell a C++ compiler that the functions it declares should be assumed to use C's linkage and naming.

一个可能简单的答案来测试,这是要做到这一点:

A likely easy answer to test this is to do this:

extern "C" {
#include "customlibrary.h"
}

在main.cpp中,而不是仅仅包括 customlibrary.h 直接。

为了让自己在两种语言工作,正确声明其功能类似于C和C ++的头,把附近的头文件的顶部以下内容:

To make the header itself work in both languages and correctly declare its functions as C-like to C++, put the following near the top of the header file:

#ifdef __cplusplus
extern "C" {
#endif

和底部附近的以下内容:

and the following near the bottom:

#ifdef __cplusplus
}
#endif

这篇关于使用C库不链接的gcc / g ++的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆