源码:https://github.com/panyingyun/cmakedemo

多个文件,多个目录,宏定义的开发和关闭

(1)建立cmakeb工程目录

cmakeb/
|-- build
|   |-- auto_build_close_macro.bat
|   |-- auto_build_close_macro.sh
|   |-- auto_build_open_macro.bat
|   `-- auto_build_open_macro.sh
|-- cmakeb.cpp
|-- CMakeLists.txt
|-- msqrt
|   |-- CMakeLists.txt
|   |-- msqrt.cpp
|   `-- msqrt.h
`-- msquare
    |-- CMakeLists.txt
    |-- msquare.cpp
    `-- msquare.h

cmakeb/cmakeb.cpp

#include <stdio.h>
#include <stdlib.h>
#include "msqrt/msqrt.h"
#include "msquare/msquare.h"

int main(int argc, char *argv[]) {
	if (argc < 3) {
		printf("Usage: input double a and  double b\n");
		return 1;
	}

	double a = atof(argv[1]);
	double b = atof(argv[2]);

#ifdef USE_SQRT
	double c = msqrt(a, b);
	printf("APP Open Macro USE_SQRT\n");
	printf("sqrt(%f) + sqrt(%f) = %f\n", a, b, c);
#else
	printf("APP Close Macro USE_SQRT\n");
	double d = msquare(a, b);
	printf("square(%f) + square(%f) = %f\n", a, b, d);
#endif //USE_SQRT
	return 0;
}

cmakeb/CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
 
PROJECT(cmakeb)

option(USE_SQRT  "Set to switch to build use USE_SQRT"  ON)
if(USE_SQRT)
	add_definitions(-DUSE_SQRT)
	message(STATUS "APP OPEN MACROS USE_SQRT")
endif()


#add all source current dir
aux_source_directory(. DIR_SRCS)

add_subdirectory(msqrt)
add_subdirectory(msquare)
  
add_executable(cmakeb MACOSX_BUNDLE ${DIR_SRCS})

target_link_libraries(cmakeb msqrt msquare)

其中,USE_SQRT 由用户选择是否打开该标识,可通过cmake_gui进行配置或者命令行配置

add_definitions 指示增加宏定义

message(STATUS “APP OPEN MACROS USE_SQRT”) 指示输出一条打印信息,如果宏USE_SQRT打开, 则打印该条信息,从下面的编译日志中可以看到这一条信息

add_subdirectory 指示还有子CMakeLists.txt

target_link_libraries 指示链接的库

cmakeb/msqrt/CMakeLists.txt

#add all source current dir
aux_source_directory(. DIR_MSQRT_SRCS)
add_library(msqrt ${DIR_MSQRT_SRCS})

cmakeb/msqrt/msqrt.cpp

#include "msqrt.h"

double msqrt(double a, double b) {
	return sqrt(a) + sqrt(b);
}

cmakeb/msqrt/msqrt.h

#ifndef _MSQRT_H
#define _MSQRT_H

#include <math.h>
double msqrt(double a , double b);

#endif //_MSQRT_H

cmakeb/msquare/msquare.cpp

#include "msquare.h"

double msquare(double a, double b) {
	return (a*a + b*b);
}

cmakeb/msquare/msquare.h

#ifndef _MSQUARE_H
#define _MSQUARE_H

#include <math.h>
double msquare(double a , double b);

#endif //_MSQUARE_H

cmake2/msquare/CMakeLists.txt

#add all source current dir
aux_source_directory(. DIR_MSQRT_SRCS)
add_library(msquare ${DIR_MSQRT_SRCS})

(2) windows下 cmake编译

关闭宏定义USE_SQRT编译

cmake -G "Visual Studio 15 2017 Win64"  -DUSE_SQRT=OFF  ..
cmake --build . --config Release

打开宏定义USE_SQRT编译

cmake -G "Visual Studio 15 2017 Win64"  -DUSE_SQRT=ON  ..
cmake --build . --config Release

(3) Linux下 cmake编译

关闭宏定义USE_SQRT编译

cmake -DUSE_SQRT=OFF  ..
cmake --build . 

打开宏定义USE_SQRT编译

cmake -DUSE_SQRT=ON  ..
cmake --build . 

编译

首先编译链接两个静态库 libmsquare.a和libsqrt.a,然后编译链接可执行文件cmakeb

除了cmake命令行打开和关闭宏定义,也可以使用gui打开和关闭

CMake GUI工具配置宏定义