代码结构
代码
外层CMakeLists.txt
cmake_minimum_required(VERSION 3.5)
project(test)
option(FANGFA1 "fangfa 1" ON)
if (FANGFA1 STREQUAL "ON")
# 方法1
add_library(MyMath INTERFACE)
add_subdirectory(math)
message("方法1")
else()
# 方法2
add_subdirectory(math)
message("方法2")
endif()
include_directories(math)
aux_source_directory(. SRC)
add_executable(${CMAKE_PROJECT_NAME} ${SRC})
target_link_libraries(${CMAKE_PROJECT_NAME} MyMath)
main.c
#include <stdio.h>
#include "math.h"
int main()
{
printf("a is %d\n", add(5,6));
return 0;
}
内层CMakeLists.txt
# 方法1
# target_sources(MyMath INTERFACE
# ${CMAKE_SOURCE_DIR}/math/math.c)
# 方法2
# aux_source_directory(. SRC)
# add_library(MyMath ${SRC})
if (FANGFA1)
# 方法1
target_sources(MyMath INTERFACE
${CMAKE_SOURCE_DIR}/math/math.c)
else ()
# 方法2
aux_source_directory(. SRC)
add_library(MyMath ${SRC})
endif()
math.c
#include "math.h"
int add(int a, int b)
{
return a+b;
}
math.h
int add(int, int);
make与cmake结合使用
根目录下增加文件 Makefile ,内容如下:
PROJECT_BASE:=$(abspath $(dir $(lastword $(MAKEFILE_LIST))))
EXECUTALBE:=exefile
# make file path
OUTPUT_PATH:=$(PROJECT_BASE)/build
# default target
.DEFAULT_GOAL = all
# create exe file
$(EXECUTALBE):$(OUTPUT_PATH)/Makefile
@echo "make ..."
@# $(MAKE_COMMAND) -C $(OUTPUT_PATH)
@cmake --build $(OUTPUT_PATH) -- -j4 --no-print-directory
# create Makefile
$(OUTPUT_PATH)/Makefile:
@echo "create makefile ..."
@mkdir -p $(OUTPUT_PATH) \
&& cd $(OUTPUT_PATH) \
&& cmake $(PROJECT_BASE)
#
.PHONY: all
all:$(EXECUTALBE)
# clean
.PHONY: clean
clean:
@rm -rvf $(PROJECT_BASE)/build
.PHONY: help
help:
@echo $(MAKE)
#@echo $(MAKE_COMMAND)
则可直接在目录下执行 make即可:
root@9e010054b4b9:/home/nhf/work/learn/cmake/1# make
create makefile ...
-- The C compiler identification is GNU 9.3.0
-- The CXX compiler identification is GNU 9.3.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
方法1
-- Configuring done
-- Generating done
-- Build files have been written to: /home/nhf/work/learn/cmake/1/build
make ...
Scanning dependencies of target test
[ 33%] Building C object CMakeFiles/test.dir/main.c.o
[ 66%] Building C object CMakeFiles/test.dir/math/math.c.o
[100%] Linking C executable test
[100%] Built target test