CMake Basics: Compiling Multiple Source Files Together

CMake Basics: Compiling Multiple Source Files Together1. Multiple source files add.c and subtract.c are in one folder, the file structure is as follows:CMake Basics: Compiling Multiple Source Files Togetherhead.h

#ifndef _HEAD_H
#define _HEAD_H
// Add
int add(int a, int b);
// Subtract
int subtract(int a, int b);
#endif

add.c

#include <stdio.h>
#include "head.h"
// Add
int add(int a, int b) {
    return a + b;
}

subtract.c

#include <stdio.h>
#include "head.h"
// Subtract
int subtract(int a, int b) {
    return a - b;
}

1. Using the aux_source_directory function

# Set the minimum required CMake version to 3.15
cmake_minimum_required(VERSION 3.15)
# Set the project name to MyProject, version number to 1.0
project(MyProject VERSION 1.0)
# Set compilation options, set C++ standard to C++17
set(CMAKE_CXX_STANDARD 17)
# Force the compiler to support the specified C++ standard (C++17 here), error if not supported.
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Set header file directory
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
# Get all source files in the current directory and save to variable SRC_LIST
aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/src SRC_LIST)
# Create an executable named app
add_executable(app ${SRC_LIST})

CMake Basics: Compiling Multiple Source Files TogetherCMake Basics: Compiling Multiple Source Files Together2. Using the file function to search for multiple source files

# Set the minimum required CMake version to 3.15
cmake_minimum_required(VERSION 3.15)
# Set the project name to MyProject, version number to 1.0
project(MyProject VERSION 1.0)
# Set compilation options, set C++ standard to C++17
set(CMAKE_CXX_STANDARD 17)
# Force the compiler to support the specified C++ standard (C++17 here), error if not supported.
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Set header file directory
include_directories(${PROJECT_SOURCE_DIR}/include)
# Get all source files in the current directory
# Note: ${CMAKE_CURRENT_SOURCE_DIR} refers to the current directory, i.e., the directory where CMakeLists.txt is located
# GLOB pattern, search all files in the current directory
# GLOB_RECURSE means recursive search, i.e., search all subdirectories in the current directory
file(GLOB SRC_LIST ${CMAKE_CURRENT_SOURCE_DIR}/src/*.c)
# Create an executable named app
add_executable(app ${SRC_LIST})

CMake Basics: Compiling Multiple Source Files TogetherCMake Basics: Compiling Multiple Source Files Together

Leave a Comment