我只是继承了一些c++代码,这些代码是用一个包含main和其他一些函数的cpp文件编写的。还有一些.h文件包含类及其函数定义。
到目前为止,该程序是使用g++ main.cpp命令编译的。现在我已经将类分离为.h和.cpp文件,我需要使用makefile还是我仍然可以使用g++ main.cpp命令?
我只是继承了一些c++代码,这些代码是用一个包含main和其他一些函数的cpp文件编写的。还有一些.h文件包含类及其函数定义。
到目前为止,该程序是使用g++ main.cpp命令编译的。现在我已经将类分离为.h和.cpp文件,我需要使用makefile还是我仍然可以使用g++ main.cpp命令?
当前回答
现在我已经将类分离为.h和.cpp文件,我需要使用makefile还是我仍然可以使用“g++ main.cpp”命令?
如果您打算将几个文件放入Makefile中,那么一次编译几个文件是一个糟糕的选择。
通常在Makefile (GNU/Make)中,这样写就足够了:
# "all" is the name of the default target, running "make" without params would use it
all: executable1
# for C++, replace CC (c compiler) with CXX (c++ compiler) which is used as default linker
CC=$(CXX)
# tell which files should be used, .cpp -> .o make would do automatically
executable1: file1.o file2.o
通过这种方式,make只正确地重新编译需要重新编译的内容。还可以添加一些调整来生成头文件依赖项——这样make也可以正确地重建由于头文件更改而需要重建的内容。
其他回答
现在我已经将类分离为.h和.cpp文件,我需要使用makefile还是我仍然可以使用“g++ main.cpp”命令?
如果您打算将几个文件放入Makefile中,那么一次编译几个文件是一个糟糕的选择。
通常在Makefile (GNU/Make)中,这样写就足够了:
# "all" is the name of the default target, running "make" without params would use it
all: executable1
# for C++, replace CC (c compiler) with CXX (c++ compiler) which is used as default linker
CC=$(CXX)
# tell which files should be used, .cpp -> .o make would do automatically
executable1: file1.o file2.o
通过这种方式,make只正确地重新编译需要重新编译的内容。还可以添加一些调整来生成头文件依赖项——这样make也可以正确地重建由于头文件更改而需要重建的内容。
我曾经使用一个定制的Makefile编译当前目录中的所有文件,但是我必须每次都将它复制到我需要的每个目录中。
所以我创建了我自己的工具-通用编译器,它使编译许多文件的过程更容易。
在main.cpp之后列出所有其他CPP文件。
ie
g++ main.cpp other.cpp etc.cpp
等等。
或者您可以单独编译它们。然后链接所有结果”。O”文件一起。
~/In_ProjectDirectory $ g++ coordin_main.cpp coordin_funcc .cpp coordinator .h . cn
~/In_ProjectDirectory $ ./ a.t out .
... 工作! !
使用Linux Mint和Geany IDE
当我将每个文件保存到同一目录时,一个文件没有在该目录中正确保存;坐标文件。h。重新检查,它被保存为坐标。h,而不是->坐标。h。gch。那些小事。 Arg ! !
要单独编译而不需要链接,你需要添加-c选项:
g++ -c myclass.cpp
g++ -c main.cpp
g++ myclass.o main.o
./a.out