Using G++ to compile multiple .cpp and .h files
Asked Answered
Q

13

245

I've just inherited some C++ code that was written poorly with one cpp file which contained the main and a bunch of other functions. There are also .h files that contain classes and their function definitions.

Until now the program was compiled using the command g++ main.cpp. Now that I've separated the classes to .h and .cpp files do I need to use a makefile or can I still use the g++ main.cpp command?

Quiescent answered 8/7, 2010 at 9:18 Comment(1)
g++ *.cpp would be enough to compile all the cpp files since the order doesn't matter as long as we're not linking yet.Tableau
B
313

list all the other cpp files after main.cpp.

ie

g++ main.cpp other.cpp etc.cpp

and so on.

Or you can compile them all individually. You then link all the resulting ".o" files together.

Broncobuster answered 8/7, 2010 at 9:22 Comment(11)
You can even do g++ *.cpp -o outputGreensward
Is this anyhow a bad practice? I'd like to use this in my makefile.Potful
@gabriel_vincent, it's not necessarily bad practice, but it will mean that editing one file in a project of hundreds will cause the compiler to redo all the work for all the files. Compiling separately allows for incremental compilation.Solidary
@Potful You shouldn't be writing makefiles by hand to begin with. Use a proper build system like CMake instead.Emptyheaded
"Or you can compile them all individually. You then link all the resulting ".o" files together." For those here wondering "Umm how would I do that?" See the answer by @FredAKA.Bakerman
@BaummitAugen Yeah, except I just want to compile this tiny 2-file program I've written in 14 minutes, and I'd really prefer to spend 1 minute on writing a makefile instead of an hour setting up cmake.Hershberger
@PrzemekD Why would you write a Makefile for a 2-file program!? I concur with Baum in that as soon as you need a Makefile you should instead use Cmake.Tellus
I don't think there is a reason or requirement to list the source files in any specific order. What you do want though is the -o option.Tellus
@Peter-ReinstateMonica Because it's a part of my semi-automatic system for grading students' programming assignments and I want the build command to be explicit so that other TAs can understand what's going on. No need to be so dogmatic and "always" and "never" about stuff; let people have things their way.Hershberger
"Or you can compile them all individually." - Ok. Could you add how? (and also you can mention it can speedup compilation times). I will not need it myself as I will look elsewhere, but it is a bit frustrating not to see the answer in this 500k views post.Pedestrianism
listing other dependencies after main.cpp works for me, for some reasonDibbrun
K
85

To compile separately without linking you need to add -c option:

g++ -c myclass.cpp
g++ -c main.cpp
g++ myclass.o main.o
./a.out
Kleist answered 27/3, 2014 at 14:49 Comment(3)
Note if you want to control the name of the executable in the linking step just do what you usually do: g++ -o my_executable myclass.o main.oBakerman
why not simply use g++ *.cpp ?Javanese
@AnkitMishra g++ *.cpp compiles all the files, even if they haven't changed. Leaving off the -c option leaves out generating intermediate object files, main.o, myclass.o, which are the fruits of potentially heavy computation.Buffo
E
27

Now that I've separated the classes to .h and .cpp files do I need to use a makefile or can I still use the "g++ main.cpp" command?

Compiling several files at once is a poor choice if you are going to put that into the Makefile.

Normally in a Makefile (for GNU/Make), it should suffice to write that:

# "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

That way make would be properly recompiling only what needs to be recompiled. One can also add few tweaks to generate the header file dependencies - so that make would also properly rebuild what's need to be rebuilt due to the header file changes.

Eipper answered 8/7, 2010 at 11:39 Comment(2)
Isn't the first target the default target?Tellus
Also, a proper Makefile must list the header files as dependencies or you won't recompile after changing one. I am not sure whether in that case the cpp file must be listed as well, which of course is less elegant.Tellus
L
22

.h files will nothing to do with compiling ... you only care about cpp files... so type g++ filename1.cpp filename2.cpp main.cpp -o myprogram

means you are compiling each cpp files and then linked them together into myprgram.

then run your program ./myprogram

Latinize answered 18/11, 2013 at 20:36 Comment(0)
C
22

I know this question has been asked years ago but still wanted to share how I usually compile multiple c++ files.

  1. Let's say you have 5 cpp files, all you have to do is use the * instead of typing each cpp files name E.g g++ -c *.cpp -o myprogram.
  2. This will generate "myprogram"
  3. run the program ./myprogram

that's all!!

The reason I'm using * is that what if you have 30 cpp files would you type all of them? or just use the * sign and save time :)

p.s Use this method only if you don't care about makefile.

Carbine answered 9/2, 2015 at 15:59 Comment(3)
Redefinition error arises when I use this approach? Is there another way of doing same?Benedix
For redefinition error you need to use "include guards" #ifndef/#define/#endif. Or, if you are using a more modern compiler, you can use #pragma onceEat
I am using g++-10 and get a fileNotFound error using this wildcard syntax, but if I include the filenames (space delimited) with the same direcory path, it works fine... g++-10 /abs/src/path/*.cpp -o /abs/src/path/binary_file causes error work but g++-10 /abs/srs/path/file1.cpp /abs/src/path/file2.cpp -o /abs/src/path/binary_file works fine...... Whut is this madness?Eat
R
16

You can still use g++ directly if you want:

g++ f1.cpp f2.cpp main.cpp

where f1.cpp and f2.cpp are the files with the functions in them. For details of how to use make to do the build, see the excellent GNU make documentation.

Rizal answered 8/7, 2010 at 9:21 Comment(0)
T
13

As rebenvp said I used:

g++ *.cpp -o output

And then do this for output:

./output

But a better solution is to use make file. Read here to know more about make files.

Also make sure that you have added the required .h files in the .cpp files.

Trash answered 26/5, 2019 at 7:16 Comment(1)
I am using g++-10 and get a fileNotFound error using this wildcard syntax, but if I include the filenames (space delimited) with the same direcory path, it works fine... g++-10 /abs/src/path/*.cpp -o /abs/src/path/binary_file causes error work but g++-10 /abs/srs/path/file1.cpp /abs/src/path/file2.cpp -o /abs/src/path/binary_file works fine...... Whut is this madness?Eat
V
4

You can use several g++ commands and then link, but the easiest is to use a traditional Makefile or some other build system: like Scons (which are often easier to set up than Makefiles).

Vasquez answered 8/7, 2010 at 9:21 Comment(0)
G
3

If you want to use #include <myheader.hpp> inside your cpp files you can use:

g++ *.cpp -I. -o out
Garay answered 3/3, 2020 at 0:32 Comment(1)
Interestingly, I get a filenotfound error when using this wildcrd syntax, but if I include all the files by name individually, it works fine with the same base directory.Eat
G
2

You can do that using a single command assuming all the needed .cpp and .h files are in the same folder.

g++ *.cpp *.h -Wall && ./a.out

It will compile and execute at the same time.

Goodill answered 19/3, 2022 at 12:28 Comment(0)
C
1

I used to use a custom Makefile that compiled all the files in current directory, but I had to copy it in every directory I needed it, everytime.

So I created my own tool - Universal Compiler which made the process much easier when compile many files.

Cataplasm answered 17/1, 2014 at 20:51 Comment(0)
M
0

when using compiler in the command line, you should take of the following: you need not compile a header file, since header file gets substituted in the script where include directive is used. you will require to compile and link the implementation and the script file. for example let cow.h be header file and cow.cpp be implementation file and cow.cc(c++ files can have extension .cpp, .cc, .cxx, .C, .CPP, .cp) be script file. Since gcc compiler notation for c++ file is g++, we can compile and link the files using

$g++ -g -Wall cow.cpp cow.cc -o cow.out

options '-g' and '-Wall' are for debugging info and getting warning for errors. Here cow.out is the name of the executable binary file that we can execute to run the program. it is always good to name your executable file otherwise name will be automatically given which might be confusing at times. you can also do the same by using makefiles, makefiles will detect, compile and link automatically the specified files. There are great resources for compilation using command line enter link description here

Misdirection answered 13/11, 2021 at 9:37 Comment(0)
C
-4

~/In_ProjectDirectory $ g++ coordin_main.cpp coordin_func.cpp coordin.h

~/In_ProjectDirectory $ ./a.out

... Worked!!

Using Linux Mint with Geany IDE

When I saved each file to the same directory, one file was not saved correctly within the directory; the coordin.h file. So, rechecked and it was saved there as coordin.h, and not incorrectly as -> coordin.h.gch. The little stuff. Arg!!

Cooperstein answered 17/5, 2016 at 6:33 Comment(1)
You are getting downvoted because you have included h-files, which is an error.Bakerman

© 2022 - 2024 — McMap. All rights reserved.