CMake
cmake, makefile 中定义的宏变量,其实和C/C++中的#define 是一致的,可以传入到C/C++中,控制程序的编译
比如:cmake中有:
add_definitions(-Dhello="hello cmake")
用cmake管理的C代码中有:
#ifndef hello
#define hello "hello src"
#endif
void func()
{
printf("%s\n", hello);
}
那么C代码中func函数打印的输出是: hello cmake
, 如果cmake中没有这一句定义, 该函数就打印 hello src
可见,可以在cmake中加入宏定义来控制代码的行为。
但一般上,cmake,makefile中定义的宏定义都是用来控制程序编译走向的。
完整的CMakeList.txt 和 cpp代码如下:
cmake_minimum_required(VERSION 2.8)
#C++11标准
set(CMAKE_CXX_STANDARD 11)
#C++11标准
if(CMAKE_COMPILER_IS_GNUCC)
message("COMPILER IS GNUCC")
#ADD_DEFINITIONS ( -std=c++11 -lpthread)
endif(CMAKE_COMPILER_IS_GNUCC)
set(CMAKE_CXX_FLAGES "${CMAKE_CXX_FLAGS} -std=c++11 -lpthread")
#set project name ${PROJECT_NAME}
project(cpp11_thread)
#set project version
SET(TEST_VERSION_MAJOR 1)
SET(TEST_VERSION_MINOR 0)
SET(TEST_VERSION_PATCH 0)
#**************macro definition*************************
#设置预处理宏定义开关 like:#define hello
add_definitions(-Dhello="hello cmake") #!necessary
#*******************end*********************************
#指定可执行文件生成路径
SET(EXECUTABLE_OUTPUT_PATH "${PROJECT_BINARY_DIR}/bin")
set(CMAKE_EXE_LINER_FLAGS "-static-libgcc -static-libstdc++")
add_executable(cpp11_thread ${PROJECT_SOURCE_DIR}/main.cpp)
target_link_libraries(cpp11_thread PUBLIC pthread)
C++ 代码
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#ifndef hello
#define hello "hello src"
#endif
using namespace std;
void print_hello()
{
for(int i = 0; i <= 6; ++i) {
cout << hello << endl;
std::this_thread::sleep_for(chrono::seconds(1));
}
}
int main()
{
string s = hello;
for(auto i : s) {
cout << i ;
}
thread t1(print_hello);
for(int i = 0; i <= 6; ++i) {
cout << hello << endl;
std::this_thread::sleep_for(chrono::seconds(1));
}
t1.join();
cout << endl;
return 0;
}
打印出来的是 “hello cmake", 可见, cmake中定义的宏定义,可以传入到代码工程中。