If you have a source file foo.cpp
, you can build an executable zap
from it like so:
g++ foo.cpp -o zap
Or you can build the executable in two steps, first building the object file foo.o
from foo.cpp
, then building zap
from foo.o
:
g++ -c foo.cpp -o foo.o
g++ foo.o -o zap
(The reason for doing it in two steps isn't immediately obvious, but bear with me.)
If you have two source files, foo.cpp
and bar.cpp
, you can build the executable from them like so:
g++ foo.cpp bar.cpp -o zap
or in two stages, like so:
g++ -c foo.cpp -o foo.o
g++ -c bar.cpp -o bar.o
g++ foo.o bar.o -o zap
After you have done this, suppose you modify foo.cpp
. You can rebuild zap
this way:
g++ -c foo.cpp -o foo.o
g++ foo.o bar.o -o zap
There's no reason to rebuild bar.o
, because you haven't changed bar.cpp
and you still have bar.o
left over from the earlier build.
(A utility like Make can help you manage this process, handling the different steps and keeping track of which files are up to date, but let's not try to do too much at once.)
Now, how to divide the code up into different files? This gets into the topic of a translation unit, which is subtle, but generally declarations go into header files, and a source file contains a set of related functions. If there is a class Foo
, the class definition (which includes the member function declarations) goes into Foo.h
, and the member function definitions go into Foo.cpp
.
So in your case you'd have Drink.h
:
#include <string>
using std::string;
class Drink
{
public:
void output_information();
string info;
};
Drink.cpp
:
#include "Drink.h"
#include <iostream>
using namespace std; // saves typing, but not a good idea generally
void Drink::output_information()
{
cout << "Details: " << info << endl;
}
and Main.cpp
:
#include "Drink.h"
#include <iostream>
using namespace std; // saves typing, but not a good idea generally
int main()
{
...
}