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:
#include <iostream>
#include <stdlib.h>
#include "main.h"
void print_from_external_file();
using namespace std;
using ddd::a;
int main( int argc, char* argv[])
{
a = atoi( argv[1] );
print_from_external_file();
return 0;
}
Your .h:
#include <iostream>
using namespace std;
namespace ddd
{
int a;
}
using ddd::a;
void print_from_external_file()
{
cout << a << endl;
}
Alternatively you can get rid of the namespace, and use extern int a
in your .cpp file to get access to the variable:
.cpp
#include <iostream>
#include <stdlib.h>
#include "main.h"
void print_from_external_file();
using namespace std;
extern int a;
//the rest goes unchanged
.h:
#include <iostream>
using namespace std;
int a;
//the rest goes unchanged