【问题标题】:CMake, UnitBuild specific compile optionsCMake、UnitBuild 特定的编译选项
【发布时间】:2014-11-30 12:43:27
【问题描述】:

我有一个文件夹结构的项目:

ProjectRoot/
ProjectRoot/Folder1
ProjectRoot/Folder2

目前我位于 ProjectRoot 中的 Cmake 文件看起来像这样

#I'm not proficient with Cmake, so I force recent version to prevent me debuggin
#problems for users that use old Cmake versions.

cmake_minimum_required( VERSION 2.8)
project( Project)

add_definitions( -DPROJECT_BUILD_DLL)


if(MINGW)
    add_compile_options( -Os -Wall -Wextra)
endif()

add_subdirectory( ProjectRoot/Folder1)
add_subdirectory( ProjectRoot/Folder2)


add_library( libProject SHARED $<TARGET_OBJECTS:ProjectRootObj>
                               $<TARGET_OBJECTS:ProjectRootFolder1Obj>)

对于每个子文件夹,我都有一个这样的文件:

cmake_minimum_required( VERSION 2.8)
project( ProjectRoot_Folder1)

# find source files
file(GLOB sourceFiles
"*.cpp"
)

# Exclude them from build
set_source_files_properties(${sourceFiles} PROPERTIES HEADER_FILE_ONLY true)

# Create single source file
set(unit_build_file ${CMAKE_CURRENT_BINARY_DIR}/all.cpp)
file( WRITE ${unit_build_file} "// autogenerated by CMake\n")

foreach(source_file ${sourceFiles} )
    file( APPEND ${unit_build_file} "#include \"${source_file}\"\n")
endforeach(source_file)



# Add compiler and unit-build specific settings
if(MINGW)
  add_compile_options( -Wzero-as-null-pointer-constant  
                       -Wold-style-cast
                   )
endif()

add_library( ProjectRootFolder1Obj OBJECT all.cpp )

构建成功。但是我有一个讨厌的问题,在子文件夹中设置的编译器选项适用于“项​​目范围”(每个 CMakeLists.txt 文件中的选项也被“添加”到其他文件中!)

Folder2 中的源代码是一个自动生成的 OpenGL 源文件 (GLLoadGen),因此我希望它在没有编译选项的情况下进行编译(从另一个 CMakeLists.txt 文件设置在另一个文件夹中):

-Wzero-as-null-pointer-constant  
-Wold-style-cast

因为它会产生数百条警告。无论我添加子文件夹的顺序如何,似乎“编译器选项”都适用于项目范围,这意味着如果我编译

文件夹 1 与

-O1

文件夹 2 与

-O2

通过查看生成的 Makefile,我发现“-O1”和“-O2”都被用作两个文件夹的命令行选项!而我想为每个文件夹使用不同的编译选项,因为每个文件夹都是不同的编译单元,需要不同的警告和优化级别。

这对我来说似乎是一个 Cmake 问题,因为我遵循了他们关于 OBJECT 目标的教程,其中明确指出“为每个对象使用不同的编译器选项”。那我错过了什么?

学分:

  • 我一直在我的项目中使用统一构建,我现在使用 Cmake 来自动生成“all.cpp”(我之前使用 bash 脚本做过),使用此页面上的教程:enter link description here

【问题讨论】:

    标签: c++ cmake


    【解决方案1】:

    经过调查,我终于找到了解决方案。问题不是子文件夹的相对顺序,而是“add_compile_options”的顺序。 要为每个子目录实现不同的编译选项,我必须执行以下操作:

    #options seen by subfolders
    if(MINGW)
        add_compile_options( -Os -Wall -Wextra) 
    endif()
    
    add_subdirectory( ProjectRoot/Folder1)
    add_subdirectory( ProjectRoot/Folder2)
    
    #options seen only by current target (if any file compiled here)
    if(MINGW)
        add_compile_options( -Wzero-as-null-pointer-constant  
                             -Wold-style-cast)
    endif()
    

    问题是 CMakeLists.txt 添加了一些文件夹,其中“add_compile_options”在错误的位置。

    基本上我的解决方案/建议:避免递归添加 CMakeLists.txt 使用根“CMakeLists.txt”并包含其中的所有子文件夹。保持项目很多 更简单(您在添加新文件夹时只有一个编辑位置,而不是查找要编辑的 N 个文件以包含它们的“子”)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-07
      • 2017-11-01
      • 2019-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多