项目链接和编译文件

时间:2021-07-08 15:07:44

标签: c++ cmake g++

我想开始构建一个项目,我有以下文件夹结构(至少是其中的一部分):

lib
|---class1.cpp
|---class1.hpp
src
|---main.cpp

我有 MinGW 编译器,但我不知道如何编译所有 .cpp 文件。我知道用于编译所有文件的命令 g++ *.cpp -o main,但仅适用于同一文件夹中的文件。

我应该将所有文件移动到 src 文件夹吗?我应该改变项目结构吗? 另外,我真的很怀疑我是否应该使用 CMake。

1 个答案:

答案 0 :(得分:1)

对于准系统项目,您的结构很好。只需将以下 CMakeLists.txt 文件添加到目录的根目录:

cmake_minimum_required(VERSION 3.5)

# Given your project a descriptive name
project(cool_project)

# CHoose whatever standard you want here... 11, 14, 17, ...
set(CMAKE_CXX_STANDARD 14)

# The first entry is the name of the target (a.k.a. the executable that will be built)
# every entry after that should be the path to the cpp files that need to be built
add_executable(cool_exe src/main.cpp lib/class1.cpp)

# Tell the compiler where the header files are
target_link_libraries(cool_exe PRIVATE lib)

您的目录现在应该看起来像

CMakeLists.txt
lib
|---class1.cpp
|---class1.hpp
src
|---main.cpp

然后要构建项目,您通常会

  1. 创建一个文件夹,您可以在其中构建所有内容(通常称为 build,但这取决于您)。现在目录看起来像

     CMakeLists.txt
     lib
     |---class1.cpp
     |---class1.hpp
     src
     |---main.cpp
     build
    
  2. 进入 build 文件夹,然后在类似命令上,使用命令 cmake .. 配置您的项目(只是重申...这需要从 build 文件夹内完成)。

  3. 使用 make 命令构建您的项目(再次从构建文件夹中)。

之后,您应该在构建文件夹中有一个名为 cool_exe 的可执行文件。

相关问题