Reputation: 135
I have a main code (.cpp
) and some other files (.cpp
and their corresponding .h
file) which contain the function that are used in my main program. I'd like to know how to compile my files and run the main code.
Upvotes: 5
Views: 17362
Reputation: 183514
This depends on your compiler. For example, with GCC you might write:
g++ foo.cpp bar.cpp baz.cpp -o foo # compile program
./foo # run program
Upvotes: 8
Reputation: 104080
Basile's right on, you need build machinery to have software you can easily work on. You really want to be able to just run make
or something similar and get your project re-built quickly in a repeatable fashion. You also want to make sure that your entire project is kept up to date, rebuilding everything that depends upon something that has changed. While you could just keep around a shell script containing g++
lines as in ruakh's answer, this will needlessly recompile more than you need. (Which isn't a big deal with small projects but becomes important when projects grow larger than trivial.)
I've only taken fifteen minutes to skim the OMake documentation, but it looks very promising. make
is standard on systems and provides a huge array of pre-defined build rules, including rules for C++, so it isn't very difficult to write new Makefile
s for projects.
It'll look something like this:
# the compiler and its flags
CXX = g++
CXXFLAGS = -Wall
PROGRAM = foo
OBJECTS = foo_a.o foo_b.o foo_c.o foo_d.o
.PHONY: all
.DEFAULT: all
all: $(PROGRAM)
$(PROGRAM): $(OBJECTS)
The objects foo_a.o
will be built from a corresponding source file named foo_a.c
, foo_a.cc
, foo_a.C
, foo_a.cpp
, foo_a.p
, foo_a.f
, foo_a.F
, etc., for C, C++, Fortran, Pascal, Lex, Yacc, and so on.
The O'Reilly make
book is sadly quite dated at this point; the .SUFFIX
rules have been supplanted by pattern rules, but there is no coverage of pattern rules in the O'Reilly book. That said, it is still a good starting point if the full GNU Make documentation isn't a good fit for you.
Upvotes: 6
Reputation: 1
But the real answer is to use some build machinery, like e.g. have a Makefile and use GNU Make.
There are some better builder than GNU Make, like Omake
Builders are very useful, because in the example by ruakh you may don't want to recompile foo.cpp
when only bar.cpp
changed so you need to take dependencies into account.
(and there are Makefile generators, like automake
, cmake
...)
Upvotes: 1