菜鸟笔记
提升您的技术认知

CMake 含参编译

阅读 : 2121

目录结构

├── cmakeLists.txt
└── main.c

源文件

main.c

#include <stdio.h>
int main(int argc, char *argv[])
{
  
    printf("compile-flags:cmake\r\n");
   // only print if compile flag set
#ifdef EX2
  printf("Hello Compile Flag EX2!\r\n");
#endif

#ifdef EX3
  printf("Hello Compile Flag EX3!\r\n");
#endif
    return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.5)

# Set a default C++ compile flag
#set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DEX2" CACHE STRING "Set C Compiler Flags" FORCE)
add_compile_options(-DEX2)
# Set the project name
project (compile_flags)

# Add an executable
add_executable(cmake_examples_compile_flags main.c)

target_compile_definitions(cmake_examples_compile_flags 
    PRIVATE EX3
)

第二行中add_compile_options 给编译链增加编译参数。
例如:add_compile_options(-std=c++11)
#在编译选项中加入c++11支持

编译

	$  mkdir build
	$  cd build/
	$  cmake .. 
	$  make VERBOSE=1 (打印详细的编译信息)
	./cmake_examples_compile_flags
	compile-flags:cmake
	Hello Compile Flag EX2!
	Hello Compile Flag EX3!