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

问题描述 投票:0回答:1

我正在用 C++ 做一个更复杂的项目,但是这里的示例与我需要的相同,并且示例的名称只会更改,但是,再次,与我正在做的事情是相同的。假设我有这个文件结构:

|--project/
|--main.cpp
|--include/
|      |--class1.hpp
|      |--class2.hpp
|--impl/
|      |--class1.cpp
|      |--class2.cpp

Class2 具有 class1 依赖性。

class1.hpp

#ifndef CLASS1_HPP
#define CLASS1_HPP

class class1 {
private: string name;
}

#endif

class2.hpp

#ifndef CLASS2_HPP
#define CLASS2_HPP

#include "class1.hpp"

class class2 {
private: Class1 class1;
}

#endif

class1.cpp

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

(functions implemantations...)

}

class2.cpp

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

(functions implemantations...)

}

主.cpp

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

int main() {
    Class2 class2;
    (...)
    return 0;
}

就是我的.hpp和.cpp在不同的目录下,如何编译不同目录下的类?

c++ oop compilation g++
1个回答
0
投票

只需从终端编译

查看

g++
命令帮助:

gcc -help | grep " \-I"
  -I-                     Restrict all prior -I flags to double-quoted inclusion and remove current directory from include path
  -I <dir>                Add directory to the end of the list of include search paths

你可以像这样编译你的代码:

g++ -Wall -Iinclude main.cpp impl/class1.cpp impl/class2.cpp -o project

但是这样太复杂了,尤其是需要多次编译测试的时候。

使用自动化工具

一般来说有2种选择:make和cmake

为了您的理解,以下解决方案是简化的解决方案,但并不是很优雅

制作

all: main.o class1.o class2.o
    gcc -Wall main.o class1.o class2.o -o project

main.o: main.cpp
    gcc -c -Wall main.cpp -o main.o

class1.o: impl/class1.cpp
    gcc -c -Wall -Iinclude impl/class1.cpp -o class1.o

class2.o: impl/class2.cpp
    gcc -c -Wall -Iinclude impl/class2.cpp -o class2.o

clean:
    rm -f project main.o class1.o class2.o

将其放在您的

project
目录下,将其命名为
Makefile
,然后运行:
make

❯ make
gcc -c -Wall main.cpp -o main.o
gcc -c -Wall -Iinclude impl/class1.cpp -o class1.o
gcc -c -Wall -Iinclude impl/class2.cpp -o class2.o
gcc -Wall main.o class1.o class2.o -o project

将显示名为

project
的可执行文件

CMake

cmake_minimum_required(VERSION 3.15)

project(project)

add_executable(project 
  main.cpp
  impl/class1.cpp 
  impl/class2.cpp
)
target_include_directories(project PRIVATE include)

将其放入

project
目录并命名为
CMakeLists.txt
。运行:

cmake -B build # This generate a build dir under `project` dir and names it `build`
cmake --build build # This builds your project
© www.soinside.com 2019 - 2024. All rights reserved.