使用gcc编译的静态库中的未解析符号

时间:2011-08-02 21:32:34

标签: c++ gcc g++ linker-errors

我正在尝试使用gcc 4.2在Mac OS X上编译一些旧的C / C ++代码。最初是使用Visual Studio在Windows上编写的。我正在编译一个与其他代码链接的静态库,但我遇到了一些难以理解的链接器错误。

当我尝试针对静态库编译一些源代码时,链接器会给我以下错误:

Undefined symbols for architecture i386:
  "_read_float", referenced from:
      _sub_token_values in libcompengine.a(alparce.o)

方法read_float在库中,正在编译。但是当我使用nm将符号转储到库中时,我看到在libcompengine.a(alparce.o)下,方法_read_float显示为未定义:

U _read_float 

然后在应该定义read_float的文件中,它出现了一个错误的名称:

00000686 t __ZL10read_floatPKj

有人可以给我任何提示,说明为什么这种方法没有得到正确解决?我花了半天时间尝试各种gcc编译器和源标志,但不幸的是,我还没有找到一个成功的组合。

1 个答案:

答案 0 :(得分:2)

如果您计划使用C ++库与C进行交互,请务必标记C程序将要调用的函数。

我已经完成了以下操作(虽然还有其他方法)

#ifndef INCLUDE_FILE_NAME_H
#define INCLUDE_FILE_NAME_H

// Insert this before any global function defintitions
#ifdef __cplusplus
extern "C" {
#endif

float read_float();

// Insert after all global function defintions
#ifdef __cplusplus
}
#endif
#endif

这样做是告诉编译器extern“C”{}行之间的所有外部函数定义都应该使用C链接。它只在使用C ++编译时添加了额外的定义。另一种选择是执行类似下面的操作,它基本上允许您指定应该使用C链接的功能,哪些不应该。

#ifdef __cplusplus
#define C_LINKAGE "C"
#else
#define C_LINKAGE
#endif

extern C_LINKAGE float read_float();
相关问题