C++ 对函数 CMake 的未定义引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38530491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Undefined reference to function CMake
提问by Exagon
I am trying to learn CMake, but I get a undefined reference to ... linker error I have a directory with a subdirectory. each of them has its own CMakeLists.txt
我正在尝试学习 CMake,但我得到了一个未定义的引用...链接器错误 我有一个带有子目录的目录。他们每个人都有自己的 CMakeLists.txt
test
|----main.cpp
|----CMakeLists.txt
|----test2
|----foo.hpp
|----foo.cpp
|----CMakeLists.txt
the CMakeLists.txt for test is:
用于测试的 CMakeLists.txt 是:
cmake_minimum_required(VERSION 3.5)
project(tests)
add_subdirectory(test2)
set(SOURCE_FILES main.cpp)
add_executable(tests ${SOURCE_FILES})
the CMakeLists.txt for test2 is:
test2 的 CMakeLists.txt 是:
set(test2_files
foo.cpp
foo.hpp
)
add_library(test2 ${test2_files})
foo.cpp
implements a function which is defined in foo.hpp
for this function I am getting the undefined reference error.
What am I doing wrong? How can I get rid of this linker error
foo.cpp
实现了一个foo.hpp
为此函数定义的函数,我收到未定义的引用错误。我究竟做错了什么?我怎样才能摆脱这个链接器错误
EDIT: My CMakeLists.txt now looks like this, but I still get the linker error:
编辑:我的 CMakeLists.txt 现在看起来像这样,但我仍然收到链接器错误:
project(tests)
cmake_minimum_required(VERSION 2.8)
set(SOURCE_FILES main.cpp)
include_directories(test2)
link_directories(test2)
add_subdirectory(test)
add_executable( ${PROJECT_NAME} ${SOURCE_FILES} )
target_link_libraries(${PROJECT_NAME} test2)
I also tried it with the absolute path instead of test2
我也用绝对路径而不是 test2
EDIT: solved it it was only a typo in the CMakeLists.txt of test2.
编辑:解决了它只是 test2 的 CMakeLists.txt 中的一个错字。
回答by davepmiller
Make sure that your test CMakeLists.txt
links to the created library.
确保您的测试CMakeLists.txt
链接到创建的库。
project(test)
cmake_minimum_required(VERSION 2.8)
set(SOURCE_FILES main.cpp)
include_directories( test2 )
#here
link_directories(test2)
add_subdirectory(test2)
add_executable( ${PROJECT_NAME} ${SOURCE_FILES} )
#and here
target_link_libraries( ${PROJECT_NAME} test2 )
回答by kivi
Function add_subdirectory($dir)
does not automatically add $dir
to include directories and link directories. To use library test2
you should do it manually in CMakeLists.txt of test
directory:
函数add_subdirectory($dir)
不会自动添加$dir
包含目录和链接目录。要使用库,test2
您应该在test
目录的CMakeLists.txt 中手动执行:
include_directories(test2/)
link_directories(test2/)
Then, link your executable with test2
library to get functions definitions. Add to CMakeLists.txt of test
directory:
然后,将您的可执行文件与test2
库链接以获取函数定义。添加到test
目录的CMakeLists.txt 中:
target_link_libraries(tests test2)