Here is a minimal working example describing my current situation. The file main.cpp
#include <iostream>
void print_from_external_file();
using namespace std;
int main( int argc, char* argv[])
{
print_from_external_file();
return 0;
}
The file containing print_from_external_file()
#include <iostream>
using namespace std;
namespace
{
int a;
}
void print_from_external_file()
{
cout << a << endl;
}
Here is my goal: I wish to run this program by command line like “test.exe 2”. The integer 2 I want to be loaded into the variable a in the external file. Is there a way to accomplish this without having to call print_from_external_file() with argv[1]? In other words, can “a” be given the value “2” automatically?
You will have to name your namespace. Unnamed namespaces are tied to their translation units, so you will not be able to access the variable in it from another unit.
Your .cpp:
Your .h:
Alternatively you can get rid of the namespace, and use
extern int ain your .cpp file to get access to the variable:.cpp
.h: