cmake例程学习

代码结构

在这里插入图片描述

代码

外层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);

猜你喜欢

转载自blog.csdn.net/niu_88/article/details/121390535