繁体   English   中英

CMake,UnitBuild特定的编译选项

[英]CMake, UnitBuild specific compile options

我有一个结构化的文件夹结构:

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脚本进行过此生成): 在此处输入链接说明

经过调查,我终于找到了解决方案。 问题不是sub_folders的相对顺序,而是“ 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个文件以包含其“子项”)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM