cmake条件编译
目录结构
Add.cc是加法,Mul.cc是乘法,main.cc通过条件宏进行调用,在CMakeLists.txt中通过option进行控制
代码
cal.h
#ifndef _CAL_H #define _CAL_H #include <iostream> using namespace std; void Add(int a,int b); void Mul(int a,int b); #endif
Add.cc
#include "cal.h" void Add(int a,int b) { cout<<"[Add result]: "<<a+b<<endl; }
Mul.cc
#include "cal.h" void Mul(int a,int b) { cout<<"[Mul Result]: "<<a*b<<endl; }
main.cc
#include "cal.h" int main(void) { cout<<"[System]: input first number"<<endl; int a; cin>>a; cout<<"[System]: input second number"<<endl; int b; cin>>b; #ifdef _ADD Add(a,b); #endif #ifdef _MUL Mul(a,b); #endif #ifndef _ADD #ifndef _MUL cout<<"[System message]: None"<<endl; #endif #endif return 0; }
CMakeLists.txt
cmake_minimum_required(VERSION 3.18) project(test) include_directories(${PROJECT_SOURCE_DIR}/inc) option(ADD "calculate a+b" ON) option(MUL "calculate a*b" ON) set(SRC_DIR ${PROJECT_SOURCE_DIR}/src) set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin) if(ADD AND MUL) add_compile_options(-D_ADD) add_compile_options(-D_MUL) set(SRC_LIST ${SRC_DIR}/main.cc ${SRC_DIR}/Add.cc ${SRC_DIR}/Mul.cc) add_executable(cal ${SRC_LIST}) message("ADD AND MUL") endif() if(ADD AND (NOT MUL)) add_compile_options(-D_ADD) set(SRC_LIST ${SRC_DIR}/main.cc ${SRC_DIR}/Add.cc) add_executable(add ${SRC_LIST}) message("ADD AND (not MUL)") endif() if((NOT ADD) AND MUL) add_compile_options(-D_MUL) set(SRC_LIST ${SRC_DIR}/main.cc ${SRC_DIR}/Mul.cc) add_executable(mul ${SRC_LIST}) message("(not ADD) AND MUL") endif() if((NOT ADD) AND (NOT MUL)) set(SRC_LIST ${SRC_DIR}/main.cc) add_executable(none ${SRC_LIST}) message("(NOT ADD) AND (NOT MUL)") endif()
同时调用加法乘法
sudo cmake -DADD=ON -DMUL=ON ..
sudo cmake
只调用加法
sudo cmake -DADD=ON -DMUL=OFF ..
sudo make
只调用乘法
sudo cmake -DADD=OFF -DMUL=ON ..
sudo make
两个都不调用
sudo cmake -DADD=OFF -DMUL=OFF ..
sudo make
无情的摸鱼机器