Lot of textbooks don't explain at all how to split source code in multiple modules -.-
As MikeBoy said you must learn the difference of a header file and a .cpp file.
for example.... here there is a very very simple example about a simple project splitted in three modules.
Class Car, void ice(); and main module :)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
// Car.h
#ifndef HEADER_CAR_H
#define HEADER_CAR_H
#include <string>
class Car {
int speed;
std::string color;
int doors;
public:
void set_speed(int val);
const int get_speed();
void define_color(std::string &val);
const std::string get_color();
void define_doors_number(int val);
const int get_doors_number();
};
#endif
| |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
//Car.cpp
#include "Car.h"
void Car::set_speed(int val) {
speed = val;
}
const int Car::get_speed() {
return speed;
}
void Car::define_color(std::string &val) {
color=val;
}
const std::string Car::get_color() {
return color;
}
void Car::define_doors_number(int val) {
doors=val;
}
const int Car::get_doors_number() {
return doors;
}
| |
First module is the class Car.
As you can see the header (car.h) contains only the "structure" of the class, without the source for every function members.
The #ifndef, #define, #endif lines are used to avoid multiple declarations. The #ifndef macro verify that the macro HEADER_CAR_H is defined or not, and only if not defined add the declaration and defines HEADER_CAR_H. With this teqnique, even if you include multiple times this header, you will not encounter multiple definition error.
The .cpp files need to know the class Car "structure"... this is why we include there Car.h
----------------
1 2 3 4 5 6 7 8
|
//ice.h
#ifndef HEADER_ICE_H
#define HEADER_ICE_H
void ice();
#endif
| |
1 2 3 4 5 6 7 8
|
//ice.cpp
#include <iostream>
#include "ice.h"
void ice() {
std::cout<<"ICE!";
}
| |
----------------------------------
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
//main.cpp
#include "Car.h"
#include "ice.h"
#include <iostream>
int main() {
Car mycar;
std::string mycolor="red";
mycar.define_color(mycolor);
mycar.define_doors_number(5);
mycar.set_speed(50);
std::cout<<"color: "<<mycar.get_color()<<"\n";
std::cout<<"doors: "<<mycar.get_doors_number()<<"\n";
std::cout<<"spped: "<<mycar.get_speed()<<"\n";
ice();
return 0;
}
| |
------------------------------------------------------------
compiling:
g++ -c -o Car.o Car.cpp
g++ -c -o ice.o ice.cpp
g++ -c -o main.o main.cpp
linking:
g++ -o test.exe main.o Car.o ice.o
----------------------------------------
As you can see, the module main can use both void ice() and class Car becouse it includes headers.
Heders declare only the funcion and the class, in this example, so "void main" can know them.
But the actual code of "void ice()" and "class Car" are contained in a separated .cpp, separately compiled.