当我尝试编译时,我再次收到“undefined symbols for architecture x86_64”错误。我已经尝试了比我在这篇文章中实际记录的更多的东西(因为我已经忘记了我尝试过的所有内容)。这是一个非常简单的设置,应该使用 CMake 很容易编译...
当我对此运行 make 时,它工作得很好。但我想将其转换为 CMake 以实现互操作性。如您所见,我在几个地方放置了“${HEADERS}”变量,我已经尝试了很多位置,但我一直收到错误。根据我放置 ${HEADER} 的位置,它在技术上还可以生成“错误:生成多个输出文件时无法指定 -o”的错误(如果它 仅 位于 target_link_library 声明中,则适用) .
我有 2 个文件夹:
Root
Headers (contains all .h files)
Source (contains all .cc/.cpp/.c files) (and also a CMakeLists.txt)
CMakeLists.txt
我的根 CMakeLists.txt 包含以下内容:
cmake_minimum_required(VERSION 2.8.4)
project(Framework)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
add_compile_options("-v")
add_subdirectory(Source)
#Variables for making my life easier and adding the headers
set(H Headers)
include_directories(${H})
set(S Source)
file(GLOB HEADERS
#Add any file in the headers dir
"${H}/*"
)
# Create a variable to use for main.cc
set(MAIN ${S}/main.cc ${HEADERS})
# Add the main.cc file and headers
add_executable(Framework ${MAIN} ${HEADERS})
# Add the .cc/.cpp files
target_link_libraries(Framework ${SOURCE_FILES})
我的源目录中的 CMakeLists.txt 包含以下内容:
file(GLOB SOURCES
"*.cc"
"*.cpp"
)
add_library(SOURCE_FILES ${SOURCES})
根据我的看法,我在标题中没有一个,文档说明我们不需要。
感谢您的帮助。我看过:
- cmake including h files from other directories
- http://www.cmake.org/cmake/help/v2.8.0/cmake.html (版本 2.x 和 3.x)
- CMake Adding Headers to Projectfile -- 有可能找到解决方案,但最终说“我不知道”:(
- 以及许多其他各种邮件列表和其他网站
最佳答案
这里的主要问题是您引用 SOURCE_FILES
目标时就好像它是一个变量一样。删除美元符号和花括号。
target_link_libraries(Framework SOURCE_FILES)
在调用 add_subdirectory
之后设置 include_directories
似乎也有点奇怪,如果这有效,我会感到惊讶。
总的来说,我认为你让事情变得比他们需要的更复杂。以下应该是所有必要的。
顶级 CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(Framework CXX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -Wextra -pedantic")
include_directories(
${PROJECT_SOURCE_DIR}/Headers
)
add_subdirectory(Source)
来源/CMakeLists.txt
# Do not use file globing because then CMake is not able to tell whether a file
# has been deleted or added when rebuilding the project.
set(HELLO_LIB_SRC
hello.cc
)
add_library(hello ${HELLO_LIB_SRC})
set(MAIN_SRC
main.cc
)
add_executable(hello_bin ${MAIN_SRC})
target_link_libraries(hello_bin hello)
Headers/hello.h
#pragma once
#include <string>
namespace nope
{
std::string hello_there();
}
来源/hello.cc
#include <hello.h>
namespace nope
{
std::string hello_there()
{
return "Well hello there!";
}
}
来源/main.cc
#include <hello.h>
#include <iostream>
int main()
{
std::cout << nope::hello_there() << std::endl;
return 0;
}
不要担心构建文件夹中文件的放置。这是安装步骤要弄清楚的。
$ mkdir build && cd build
$ cmake -DCMAKE_BUILD_TYPE=Debug ..
$ make
关于c++ - CMake 在 include_directories 中找不到正确的头文件/包含文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26937085/