简体   繁体   English

如何在子目录内使用.cpp和.h文件?

[英]How to use .cpp and .h files inside subdirectories?

This is the contents of a directory in my system: 这是我系统中目录的内容:

/directory/
    classes/
        class1.cpp
        class1.h
    main.cpp

And here is the contents of above files: 这是上述文件的内容:

main.cpp main.cpp

   #include "classes/class1.h"

   int main(){
       class1 test;
       return 0;
   }

class1.h class1.h

   class class1 {
       public:
           class1();
           void test();
   };

class1.cpp class1.cpp

   #include "class1.h"

   class1::class1(){
   }
   class1::test(){
   }

The question is why I can't compile main.cpp ? 问题是为什么我不能编译main.cpp

ghasemi@ghasemi-MS-7693:~/Desktop/directory$ g++ *.cpp
/tmp/ccEvIogL.o: In function `main':
main.cpp:(.text+0x1f): undefined reference to `class1::class1()'
collect2: error: ld returned 1 exit status

In your main directory there is only one .cpp file, and the * wildcard doesn't look in sub-directories. 在您的主directory中只有一个.cpp文件,并且*通配符不在子目录中查找。 You need to explicitly name all the source files, or use multiple wildcards (not something I recommend). 您需要显式命名所有源文件,或使用多个通配符(我不建议这样做)。

So something like 所以像

g++ main.cpp classes/class1.cpp

What you are searching for is not related to the compiler (gcc) itself but to a build environment. 您要搜索的内容与编译器(gcc)本身无关,而与构建环境有关。 There are several tools which do the job. 有几种工具可以完成这项工作。

If you start with only a hand full of files, you can compile every file every time. 如果仅从一堆文件开始,则可以每次编译每个文件。 But if your projects become bigger it is very time consuming to compile all files again and again, also if nothing has changed in some of them! 但是,如果您的项目变大,那么一次又一次地编译所有文件非常耗时,而且如果其中某些文件没有任何变化!

Most common for this job is gnu make. 这项工作最常见的是gnu make。

You have to write a configuration which describes your project. 您必须编写一个描述您的项目的配置。 This file is typically called "Makefile". 该文件通常称为“ Makefile”。

Here you define: Which files must be compiled if a file changes. 您在此处定义:如果文件更改,则必须编译哪些文件。 Which files must be linked together. 哪些文件必须链接在一起。 All parameters for linkage and compile for all or individual files. 用于链接和编译所有或单个文件的所有参数。 ... a lot more ... 多很多

So please take a look for https://www.gnu.org/software/make/manual/ 因此,请查看https://www.gnu.org/software/make/manual/

For your project, it can be look like: 对于您的项目,它可能类似于:

all: myprog

main.o: main.cpp classes/class1.h

classes/class1.o: classes/class1.cpp classes/class1.h

myprog: main.o classes/class1.o
    g++ main.o classes/class1.o -o myprog

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM