c++ - 在 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 上构建它会产生错误。
我尝试了以下方法:
- 在 OS X 上使用 g++ 构建
- 使用“libc++”标志
- 没有 CLion 的构建
我的环境:
- OSX 10.15.7
- 克莱恩 2020.2.4
如果这是一个非常垃圾的问题,我很抱歉。我试图谷歌这两天了,我找不到任何答案。
我知道我可以改变我的 cmake target_link_libraries(Test lib2) -> target_link_libraries(lib lib2)
,但我想知道为什么这在 Linux 上运行而不是在 OS X 上运行。
编辑:添加 .cpp 源并包括
解决方案
如果 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 上编译运行良好。
推荐阅读
- flutter - Flutter,如何在从详细视图更新内容后更新列表视图中项目中的文本?
- typescript - 为什么 VS-Code 不能识别“__dirname”?
- c# - C# Active Directory DirectorySearcher 只找到我自己的用户
- python - 将参数传递给 itertools.groupby() 中的键函数以计算键的唯一值
- sass - Sass darken() 中作为 $color 参数的函数值
- python - 如何使用 fillConvexPoly 从所有轮廓制作遮罩
- java - 我应该如何在删除后将用户 ID(或其他参数)传递给 PSQL 触发器?
- aem - 如何在 AEM Template 中使用参考组件
- haxe - 使用 haxe 编辑远程文件?
- javascript - 尝试添加 slideToggle() 功能但它不起作用