首页 > 解决方案 > 在 OS X 上使用 c++ 链接问题

问题描述

我的问题是,我想在 OS X 上编译一些 c++ 代码。在 Linux 上这工作得很好,但是如果我想在 mac 上编译它,我会收到以下错误:

Undefined symbols for architecture x86_64:
  "test2::printHelloWorld()", referenced from:
      test::printHelloWorld() in test.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

我有三个小文件,它们相互依赖,还有一个 CMAKE:

//main.cpp
#include "test.h"

int main() {
  test t;
  t.printHelloWorld(); //<- this calls printHelloWorld from test.h
  return 0;
}
//test.h
class test {
 public:
  void printHelloWorld(); //<- this calls printHelloWorld from test2.h
};
//test.cpp
#include test2.h

test::printHelloWorld(){
  test2 t;
  t.printHelloWorld();
}
//test2.h
class test2 {
 public:
  void printHelloWorld();
};
//test2.cpp
#include <iostream>

test2::printHelloWorld(){
  std::cout << "Hello World\n";
}
//CMAKE
cmake_minimum_required(VERSION 3.17)
project(Test)

set(CMAKE_CXX_STANDARD 14)
add_library(lib2 SHARED test2.cpp)
add_library(lib SHARED test.cpp)
add_executable(Test main.cpp)

target_link_libraries(Test lib)
target_link_libraries(Test lib2)

正如我所说,使用 gcc 在 Linux 上构建它可以正常工作,但在 OS X 上构建它会产生错误。

我尝试了以下方法:

我的环境:

如果这是一个非常垃圾的问题,我很抱歉。我试图谷歌这两天了,我找不到任何答案。

我知道我可以改变我的 cmake target_link_libraries(Test lib2) -> target_link_libraries(lib lib2),但我想知道为什么这在 Linux 上运行而不是在 OS X 上运行。

编辑:添加 .cpp 源并包括

标签: c++macoscmakelinker-errors

解决方案


如果 test2 依赖于 test 并且不可见,请调整您的 CMakeLists.txt

target_link_libraries(Test PUBLIC lib)
target_link_libraries(lib PRIVATE lib2)

cmake -G Ninja . && ninja && ./Test在 macOS 10.15.7 上编译运行良好。


推荐阅读