【发布时间】:2021-02-17 05:31:24
【问题描述】:
我的问题是,我想在 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)
正如我所说,在 Linux 上使用 gcc 构建它可以正常工作,但在 OS X 上构建它会产生错误。
我尝试了以下方法:
- 在 OS X 上使用 g++ 构建
- 使用“libc++”标志
- 在没有 CLion 的情况下构建
我的环境:
- OSX 10.15.7
- CLION 2020.2.4
如果这是一个非常垃圾的问题,我很抱歉。 google了两天也没找到答案。
我知道我可以更改我的 cmake target_link_libraries(Test lib2) -> target_link_libraries(lib lib2),但我想知道为什么这适用于 Linux 而不是 OS X。
编辑:添加 .cpp 源并包含
【问题讨论】:
-
你的 main.cpp 是否包含 test.h?
-
感谢您的快速回复。 @Basile:我尝试在我的终端中使用 cmake 和 make 构建它。这就是你的意思吗?
-
@adembudak:是的。我在 main.cpp 中包含了 test.h,在 test.h 中包含了 test2.h
标签: c++ macos cmake linker-errors