MacOSX共享库:架构x86_64的未定义符号

MacOSX shared libraries: Undefined symbols for architecture x86_64

本文关键字:未定义 符号 x86 共享 架构 MacOSX      更新时间:2023-10-16

我在MacOSX上使用共享库编译代码时遇到了一些麻烦。在尝试在MacOSX上编译它之前,我首先在Debian上编写了它。

代码如下:

test.hxx:

#ifndef TEST_HXX
#define TEST_HXX
namespace test
{
    class CFoo
    {
        /* data */
    public:
        CFoo (){}
        virtual ~CFoo (){}
        void bar();
    }; /* CFoo */
} /* namespace test */
#endif /* TEST_HXX */

test.cxx:

#include <iostream>
#include "test.hxx"
void test::CFoo::bar()
{
    std::cout << "Hello world!" << std::endl;
} /* bar() */

other.hxx:

#ifndef OTHER_HXX
#define OTHER_HXX
namespace other
{
    class CBar
    {
    public:
        CBar (){}
        virtual ~CBar (){}
        void foo();
    }; /* CBar */
} /* namespace other */
#endif /* OTHER_HXX */

other.cxx:

#include <iostream>
#include "test.hxx"
#include "other.hxx"
void other::CBar::foo()
{
    test::CFoo c;
    c.bar();
} /* bar() */

main.cxx:

#include "other.hxx"
int main (int argc, const char *argv[])
{
    other::CBar c;
    c.foo();
    return 0;
} /* main () */
和一个简单的makefile:
LIBTEST = libtest.so
LIBOTHER = libother.so

all: $(LIBTEST) $(LIBOTHER)
    g++ -ltest -lother -I. -L. main.cxx
libtest.so: test.o
    g++ -shared  test.o -o $(LIBTEST)
libother.so: other.o
    g++ -shared other.o -o $(LIBOTHER)
test.o: test.cxx test.hxx
    g++ -fPIC -c test.cxx
other.o: other.cxx other.hxx
    g++ -fPIC -c other.cxx
clean:
    $(RM) $(LIBOTHER) $(LIBTEST) test.o other.o a.out

所以我基本上创建了对象test.oother.o,并从它们创建了两个共享库(每个对象一个)。

other.cxx使用test.cxx中包含的类来打印Hello world

所以这个makefile和代码在我的Debian上工作得很好,但是当我试图在MacOSX上编译它时,我有一个编译错误:

g++ -fPIC -c test.cxx
g++ -shared test.o -o libtest.so
g++ -fPIC -c  other.cxx
g++ -shared other.o -o libother.so
Undefined symbols for architecture x86_64:
  "test::CFoo::bar()", referenced from:
      other::CBar::foo() in other.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [libother.so] Error 1

它编译并创建test的共享库,但在创建libother.so时失败。

当只使用一个共享库时(因此直接从testmain中打印Hello world),它工作得很好,但问题发生在使用几个共享库时…

我不是苹果用户,以前从未在MacOSX上工作过,所以我真的不明白链接是如何完成的。这个错误对我来说真的没有意义…

谢谢你帮我理解这个错误!

这是因为libother使用libtest,但您不与它链接。试着

g++ -shared other.o -o libother.so -L. -ltest

-L告诉编译器在哪里搜索库,-l链接到它。