为新手创建一个CMakeFiles.txt

时间:2013-04-26 23:59:25

标签: c++ cmake linkage

我有一个具有以下结构的项目

  /cmake_modules/
    FindSFML.cmake
  /includes/
    car.hpp
    motor.hpp
    tires.hpp
  /sources/
    car.cpp
    motor.cpp
    tires.cpp    
  /main.cpp
  /main.hpp

我有以下CMakeFiles.txt

cmake_minimum_required(VERSION 2.8)

project (MYGAME)
set (MYGAME_VERSION_MAJOR 1)
set (MYGAME_VERSION_MINOR 0)

set (EXECUTABLE_NAME "mygame")

include_directories ("${MYGAME_BINARY_DIR}")
include_directories ("${MYGAME_BINARY_DIR}/includes")
link_directories ("${MYGAME_BINARY_DIR}/sources")

add_executable(${EXECUTABLE_NAME} main.cpp)

set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake_modules" ${CMAKE_MODULE_PATH})
find_package(SFML 2.0 REQUIRED system window graphics network audio)

target_link_libraries(${EXECUTABLE_NAME} ${SFML_LIBRARIES})

当我尝试执行make时,我得到了这个

[100%] Building CXX object CMakeFiles/mygame.dir/main.cpp.o
Linking CXX executable mygame
CMakeFiles/mygame.dir/main.cpp.o: In function `main':
main.cpp:(.text+0x11): undefined reference to `mynamespace::Car::Instance()'
main.cpp:(.text+0x21): undefined reference to `mynamespace::Car::start()'
collect2: error: ld returned 1 exit status
make[2]: *** [mygame] Error 1
make[1]: *** [CMakeFiles/mygame.dir/all] Error 2
make: *** [all] Error 2

如何修复

1 个答案:

答案 0 :(得分:4)

您需要以某种方式在构建中包含其余的源(car.cpp,motor.cpp和tires.cpp)。

您可以直接将它们与main.cpp一起添加到可执行文件中:

set(MySources sources/car.cpp sources/motor.cpp sources/tires.cpp main.cpp)
add_executable(${EXECUTABLE_NAME} ${MySources})

或者你可以把它们变成一个库并链接到:

set(MyLibSources sources/car.cpp sources/motor.cpp sources/tires.cpp)
add_library(MyLib ${MyLibSources})
add_executable(${EXECUTABLE_NAME} main.cpp)
...
target_link_libraries(${EXECUTABLE_NAME} MyLib ${SFML_LIBRARIES})

还有几点需要注意:

如果可能,您应该避免使用link_directories(它自己的文档不鼓励使用它),并且通过add_executable或{{1}添加的文件列表中包含标题通常会很有帮助因为这些会出现在像MS Visual Studio这样的IDE中。