“extern” allow us using the same variable among different transition units(cpp files).

RegisterDay.cpp: here the count is declared & defined the first time in the whole program.

namespace gym {
int count;
void FirstTraining() {
count += 1;
}
}

TrainingDay.hpp: I also want to add up to the same variable count, to do so, I need to tell the program this count has already been declared somewhere (in our case, in RegisterDay.cpp).

namespace gym {
extern int count;
}

Now in TrainingDay.hpp, I have informed the existence of count, I’m able to use it in all the *.cpp files which include TrainingDay.hpp file. For example:

CardioDay.cpp:

namespace gym {
void run() {
count += 1;
}
}

--

--

Macro acts more like scripts. Macro #define A bbb replace A with bbb in the code.

#define oldmax(x, y) ((x)>(y)?(x):(y))q = oldmax(abc, 123);

After the preprocessor goes through the code, it will look like this:

q = ((abc)>(123)?(abc):(123));

Macro operators

##

The ## operator takes two separate tokens and pastes them together to form a single token.

Following macro can be used to initialize the variables in the beginning.
(Note you can use \to type in new line.)

#define INITIALIZATION(type, varname, value) \
type orig_##varname = value;

After declaration, we can use it like the follows:

#include <string>
INITIALIZATION( std::string, name, “Cindy” );
INITIALIZATION( float, weight, 55.0f );
INITIALIZATION( float, height, 166.0f );

Test for output:

std::cout <<"orig_name = " << orig_name <<endl; 
std::cout <<"orig_weight = " << orig_weight <<endl;
std::cout <<"orig_height = " << orig_height <<endl;

--

--