user2589840
user2589840

Reputation: 11

How do I compile multi-file C++ programs in all subdirectories?

I have a bunch of C++ programs each in its own sub-directory. Each sub-directory has a single C++ program in several files -- a .h and a .cpp file for each class plus a main .cpp program. I want to compile each program placing the executable in the corresponding sub-directory. (I also want to run each program and redirect its output to a file that is placed in the corresponding sub-directory but if I can get the compilation to work, I shouldn't have a problem figuring out this part.)

I'm using the bash shell on a UNIX system (actually the UNIX emulator Cygwin that runs on top of Windows).

I've managed to find on the web, a short scrip for compiling one-file programs in the current directory but that's as far as I've gotten. That script is as follows.

for f in *.cpp;
   do g++ -Wall -O2 "$f" -o "{f/.cpp/}";
done;

I would really appreciate it someone could help me out. I need to do this task on average once every two weeks (more like 8 weeks in a row, then not for 8 weeks, etc.)

Upvotes: 1

Views: 758

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490048

Unless you're masochistic, use makefiles instead of shell scripts.

Since (apparently) each executable depends on all the .h and .cpp files in the same directory, the makefiles will be easy to write -- each will have something like:

whatever.exe: x.obj y.obj z.obj
   g++ -o whatever.exe x.obj y.obj z.obj

You can also add a target in each to run the resulting executable:

 run:
     whatever.exe

With that you'll use make run to run the executable.

Then you'll (probably) want a makefile in the root directory that recursively makes the target in each subdirectory, then runs each (as described above).

This has a couple of good points -- primarily that it's actually built for this kind of task, so it actually does it well. Another is that it takes note of the timestamps on the files, so it only rebuilds the executables that actually need it (i.e., where at least one of the files that executable depends on has been modified since the executable itself was built).

Upvotes: 3

scott_fakename
scott_fakename

Reputation: 10789

Assuming you have a directory all of whose immediate subdirectories are all c++ programs, then use some variation on this...

for D in */; do cd "$D";
    # then either call make or call your g++ 
    # with whatever arguments in here
    # or nest that script you found online if it seems to
    # be doing the trick for you.
    cd ../;
done;

That will move in to each directory, do its thing (whatever you want that to be) and then move back out.

Upvotes: 0

Related Questions