How can you compile all cpp files in a directory?

余生长醉 提交于 2020-01-10 02:56:07

问题


I have a number of source files in a number of folders.. Is there a way to just compile all of them in one go without having to name them?

I know that I can say

g++ -o out *.cpp 

But when I try

g++ -o out *.cpp folder/*.cpp

I get an error.

What's the correct way to do this? I know it's possible with makefiles, but can it be done with just straight g++?


回答1:


By specifying folder/*.cpp you are telling g++ to compile cpp files in folder. That is correct.

What you may be missing is telling the g++ where to locate additional files that those cpp files #include.

To do this, tell your compiler to also include that directory with -I like this:

g++ -o out -I ./folder *.cpp folder/*.cpp

In some circumstances I have had the compiler forget what was in the root/current directory, so I manually specified it with another -I to the current directory .

g++ -o out -I . -I ./folder *.cpp folder/*.cpp



回答2:


Figured it out! :) I hate the idea of having to use make or a build system just to compile my code, but I wanted to split up my code into subfolders to keep it clean and organized.

Run this (replace RootFolderName (e.g. with .) and OutputName):

g++ -g $(find RootFolderName -type f -iregex ".*\.cpp") -o OutputName

The find command will do a recursive case-insensitive regex search (-iregex) for files (-type f). Placing this within $() will then inject the results into your g++ call. Beautiful! :)

Of course, make sure you're using the command right; you can always do a test run.


For those using Visual Studio Code to compile, I had to do this in the tasks.json args: [] of a task with "command": "g++":

"-g",
"$(find",
"code",
"-type",
"f",
"-iregex",
"'.*\\.cpp')",
"-o",
"program"

(Otherwise it would wrap the $() all in single quotes.)


(Thanks to: user405725 @ https://stackoverflow.com/a/9764119/1599699 comments)



来源:https://stackoverflow.com/questions/33662375/how-can-you-compile-all-cpp-files-in-a-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!