Most simple but complete CMake example

前端 未结 3 1893
你的背包
你的背包 2021-01-29 17:01

Somehow I am totally confused by how CMake works. Every time I think that I am getting closer to understand how CMake is meant to be written, it vanishes in the next example I r

3条回答
  •  时光说笑
    2021-01-29 17:53

    The most basic but complete example can be found in the CMake tutorial :

    cmake_minimum_required (VERSION 2.6)
    project (Tutorial)
    add_executable(Tutorial tutorial.cxx)
    

    For your project example you may have:

    cmake_minimum_required (VERSION 2.6)
    project (MyProject)
    add_executable(myexec src/module1/module1.cpp src/module2/module2.cpp src/main.cpp)
    add_executable(mytest test1.cpp)
    

    For your additional question, one way to go is again in the tutorial: create a configurable header file that you include in your code. For this, make a file configuration.h.in with the following contents:

    #define RESOURCES_PATH "@RESOURCES_PATH@"
    

    Then in your CMakeLists.txt add:

    set(RESOURCES_PATH "${PROJECT_SOURCE_DIR}/resources/"
    # configure a header file to pass some of the CMake settings
    # to the source code
    configure_file (
      "${PROJECT_SOURCE_DIR}/configuration.h.in"
      "${PROJECT_BINARY_DIR}/configuration.h"
    )
    
    # add the binary tree to the search path for include files
    # so that we will find TutorialConfig.h
    include_directories("${PROJECT_BINARY_DIR}")
    

    Finally, where you need the path in your code, you can do:

    #include "configuration.h"
    
    ...
    
    string resourcePath = string(RESOURCE_PATH) + "file.png";
    

提交回复
热议问题