【问题标题】:"undefined reference to" errors when linking static C library with C++ code将静态 C 库与 C++ 代码链接时出现“未定义的引用”错误
【发布时间】:2013-09-18 16:23:48
【问题描述】:

我有一个测试文件(仅用于链接测试),在其中我用我自己的 malloc/free 库重载了 new/delete 运算符 libxmalloc.a。但是在链接静态库时,我不断收到“未定义的引用”错误,即使我更改了test.o-lxmalloc 的顺序。但是一切都适用于链接这个库的其他 C 程序。我对这个问题感到很困惑,并感谢任何线索。

错误信息:

g++ -m64 -O3 -I/usr/include/ethos -I/usr/include/nacl/x86_64 -c -o test.o test.cpp
g++ -m64 -O3 -L. -o demo test.o -lxmalloc
test.o: In function `operator new(unsigned long)':
test.cpp:(.text+0x1): undefined reference to `malloc(unsigned long)'
test.o: In function `operator delete(void*)':
test.cpp:(.text+0x11): undefined reference to `free(void*)'
test.o: In function `operator new[](unsigned long)':
test.cpp:(.text+0x21): undefined reference to `malloc(unsigned long)'
test.o: In function `operator delete[](void*)':
test.cpp:(.text+0x31): undefined reference to `free(void*)'
test.o: In function `main':
test.cpp:(.text.startup+0xc): undefined reference to `malloc(unsigned long)'
test.cpp:(.text.startup+0x19): undefined reference to `malloc(unsigned long)'
test.cpp:(.text.startup+0x24): undefined reference to `free(void*)'
test.cpp:(.text.startup+0x31): undefined reference to `free(void*)'
collect2: ld returned 1 exit status
make: *** [demo] Error 1

我的test.cpp 文件:

#include <dual/xalloc.h>
#include <dual/xmalloc.h>
void*
operator new (size_t sz)
{
    return malloc(sz);
}
void
operator delete (void *ptr)
{
    free(ptr);
}
void*
operator new[] (size_t sz)
{
    return malloc(sz);
}
void
operator delete[] (void *ptr)
{
    free(ptr);
}
int
main(void)
{
    int *iP = new int;
    int *aP = new int[3];
    delete iP;
    delete[] aP;
    return 0;
}

我的Makefile

CFLAGS += -m64 -O3 -I/usr/include/ethos -I/usr/include/nacl/x86_64
CXXFLAGS += -m64 -O3
LIBDIR += -L.
LIBS += -lxmalloc
all: demo
demo: test.o
    $(CXX) $(CXXFLAGS) $(LIBDIR) -o demo test.o $(LIBS)
test.o: test.cpp
$(CXX) $(CFLAGS) -c -o $@ $<
clean:
- rm -f *.o demo

【问题讨论】:

  • 您是否尝试过使用extern "C" { #include &lt;dual/xalloc.h&gt; ... }
  • 看起来不错的规范,不是已经有了吗?

标签: c++ c static-libraries


【解决方案1】:

但一切都可以与链接该库的其他 C 程序配合使用。

您是否注意到 C 和 C++ 编译在目标文件级别创建不同的符号名称?它被称为“name mangling”。
(C++) 链接器会在错误消息中将未定义的引用显示为解构符号,这可能会让您感到困惑。如果您使用 nm -u 检查您的 test.o 文件,您会发现引用的符号名称与您的库中提供的名称不匹配。

如果你想使用作为外部链接的函数,这些函数是使用普通 C 编译器编译的,你需要将它们的函数声明包含在一个 extern "C" {} 块中,这会抑制 C++ 名称对内部声明或定义的所有内容的修改,例如:

extern "C" 
{
    #include <dual/xalloc.h>
    #include <dual/xmalloc.h>
}

更好的是,您可以将函数声明包装在头文件中,如下所示:

#if defined (__cplusplus)
extern "C" {
#endif

/*
 * Put plain C function declarations here ...
 */ 

#if defined (__cplusplus)
}
#endif

【讨论】:

    猜你喜欢
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    • 2018-12-18
    相关资源
    最近更新 更多