I have a program with two external files in addition to main.cpp and a header of constants. So in total four files. They contain the following code:
main.cpp
#include <iostream>
using namespace std;
int ext1_func();
int ext2_func();
int main()
{
int i;
i = ext1_func();
cout << i << endl;
i = ext2_func();
cout << i << endl;
return 0;
}
ext1.cpp
#include "const.h"
int asd1=1;
int ext1_func()
{
return temp_int;
}
ext2.cpp
#include "const.h"
int asd2 = 2;
int ext2_func()
{
return temp_int;
}
const.h
#ifndef CONST_H
#define CONST_H
const int temp_int=1;
#endif
My desired is the following:
1) Any variables declared in ext1.cpp should be known only to functions within ext1.cpp and likewise for ext2.cpp. So “asd1” must only be known to “ext1_func” and “asd2” for “ext2_func”.
2) The functions in “exp1.cpp” and “ext2.cpp” must be able to see all values defines in “const.h”
I believe that the code I have written and attached satisfies these requirements, but I would like to ask if I am doing it correctly? Is there an easier way to obtain the desired behavior than what I have suggested?
Thanks in advance.
Niles.
Within compilation unit level, the symbols you declare at “global” scope are all linked in to the global variable space.
The old way to avoid this was to declare them static. The new way is to put them into an anonymous namespace. They can also be declared static there too.
ext1.cpp
The const in the header is ok, constants declared this way have a special status, in fact that compiler can substitute in the code the value. Ideally though, you should at least wrap them in a (named) namespace to avoid polluting the global one. Modifying the value (using const_cast) would be undefined behaviour.
If it were non-const and you really wanted a global (not generally a good idea) you would need to use the extern keyword in the header, then create its instance in a single compilation unit.