C++ cmake 编译项目文件示例

目录结构

在这里插入图片描述

CMakeLists.txt

#6.build_together/CMakeLists.txt`

# 最低版本要求
cmake_minimum_required(VERSION 3.10)

# 项目信息
project(ce)

# 公共头文件目录(又叫指定头文件查找路径) 包括静态与动态 
# include_directories(account_dir)

# 添加动态库
add_library(k1 SHARED "./account_dir/Account.cpp" "./account_dir/Account.h")

# 添加可执行文件
add_executable(exe1 "./test_account/test_account.cpp")

# 添加头文件
target_include_directories(exe1 PUBLIC "./account_dir")
# 添加链接库
target_link_libraries(exe1 k1)

创建2个同级目录:test_account、account_dir、

test_account.cpp 执行文件

#include <iostream>
#include "Account.h"

int main()
{
    Account alice_account;
    std::cout << "test Account 的main函数" << std::endl;
    return 0;
}

Account.cpp 库文件

#include "Account.h"
#include <iostream>

Account::Account(/* args */)
{
    std::cout << "构造函数Account::Account()" << std::endl;
}
Account::~Account()
{
    std::cout << "析构函数Account::~Account()" << std::endl;
}

Account.h 库文件

#ifndef Account_H
#define Account_H

class Account
{
private:
    /* data */
public:
    Account(/* args */);
    ~Account();
};
#endif // Account_H

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
下面是一个使用 CMake 管理的多文件 C++ 项目示例: 假设我们有以下项目结构: ``` myproject/ ├── CMakeLists.txt ├── include/ │ ├── math.h │ └── utility.h └── src/ ├── main.cpp ├── math.cpp └── utility.cpp ``` 其,`include` 目录包含了 `math.h` 和 `utility.h` 两个头文件,`src` 目录包含了 `main.cpp`, `math.cpp`,和 `utility.cpp` 三个源文件。 现在,我们需要使用 CMake 来构建这个项目。我们可以在 `myproject` 目录下创建一个名为 `CMakeLists.txt` 的文件,并添加以下内容: ``` cmake_minimum_required(VERSION 3.10) project(myproject) # 添加头文件搜索路径 include_directories(include) # 添加源文件 add_executable(myproject src/main.cpp src/math.cpp src/utility.cpp) ``` 该 `CMakeLists.txt` 文件指定了项目的最低 CMake 版本和项目名称。`include_directories` 命令添加了头文件搜索路径,它告诉 CMake 在 `include` 目录查找头文件。最后,`add_executable` 命令指定了要编译的源文件,它告诉 CMake 编译 `main.cpp`,`math.cpp` 和 `utility.cpp` 三个源文件,并将它们链接成可执行文件 `myproject`。 完成以上步骤后,我们可以使用以下命令来构建项目: ``` mkdir build cd build cmake .. make ``` `mkdir build` 创建了一个构建目录,`cd build` 进入该目录,`cmake ..` 命令使用上面的 `CMakeLists.txt` 文件来构建项目,`make` 命令编译源代码并生成可执行文件。最终,我们可以在 `build` 目录下找到生成的 `myproject` 可执行文件。 这就是一个简单的 C++文件项目CMake 示例

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

默执_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值