You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编译C++项目中不同目录下的文件?

多目录C++项目编译方案

项目结构与代码说明

项目文件结构

project/
├── main.cpp
├── include/
│   ├── class1.hpp
│   └── class2.hpp
└── impl/
    ├── class1.cpp
    └── class2.cpp

修正后代码(原代码存在语法问题,已补全/修正)

class1.hpp

#ifndef CLASS1_HPP
#define CLASS1_HPP

#include <string>
class class1 {
private: 
    std::string name;
};

#endif

class2.hpp

#ifndef CLASS2_HPP
#define CLASS2_HPP

#include "class1.hpp"

class class2 {
private: 
    class1 class1_inst;
};

#endif

class1.cpp

#include "class1.hpp"
#include <iostream>

class1::class1() : name("default") {}

void class1::print_name() {
    std::cout << "Name: " << name << std::endl;
}

class2.cpp

#include "class2.hpp"
#include <iostream>

void class2::print_class1_name() {
    class1_inst.print_name();
}

main.cpp

#include "class2.hpp"
#include <iostream>

int main() {
    class2 class2_inst;
    class2_inst.print_class1_name();
    return 0;
}

注:原代码遗漏了<string>头文件、std::命名空间前缀、类定义分号,且存在类名大小写不一致问题,已统一修正

编译方案

1. 手动使用g++/clang++编译

在project/目录下直接执行命令,通过-I参数指定头文件搜索路径:

# g++版本
g++ -Iinclude main.cpp impl/class1.cpp impl/class2.cpp -o my_project

# clang++版本
clang++ -Iinclude main.cpp impl/class1.cpp impl/class2.cpp -o my_project

执行完成后,运行./my_project即可启动程序。

2. 使用Makefile自动化编译

在project/目录下创建Makefile:

CC = g++
CFLAGS = -Iinclude -Wall -Wextra
SRCS = main.cpp impl/class1.cpp impl/class2.cpp
TARGET = my_project

all: $(TARGET)

$(TARGET): $(SRCS)
	$(CC) $(CFLAGS) $(SRCS) -o $(TARGET)

clean:
	rm -f $(TARGET)
  • 执行make自动完成编译
  • 执行make clean删除生成的可执行文件

3. 使用CMake(适合复杂项目)

在project/目录下创建CMakeLists.txt:

cmake_minimum_required(VERSION 3.10)
project(my_project)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)

include_directories(include)
file(GLOB SRCS main.cpp impl/*.cpp)

add_executable(my_project ${SRCS})

然后执行以下命令完成编译:

mkdir build && cd build
cmake ..
make

编译后的可执行文件位于build/目录下,运行./my_project即可。

内容的提问来源于stack exchange,提问作者Ramon Jales

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 22:30:17