Namespaces and include files in c++

This is a common situation (at least for me): you have a set of parameters that are basically global to the program. But, of course, it is not good to go totally global, so one may try a namespace, thus:

namespace fun {
double f(double);
int i=5;
}

This way, one can keep simple names (“f” and “i”), but still call them fun::f, and fun::i. This is ok as long as one has one source cpp file (or one include file, included only once). What happens when one splits the code into several files, as one should eventually? f() is fine, but i get defined twice… error!

The way to go: simple, just use extern!. Examples follow.

file “defs.h”

#include<iostream>

using std::endl;
using std::cout;

namespace fun {
double f(double);
extern int i;
}

file “defs.cpp”

#include”defs.h”

namespace fun {
double f(double x) {
return 2*x;
}

int i=5;

}

// or just:
//double fun::f(double x) {
//int  fun::i=5;

file “main.cpp”

#include”defs.h”

int main(void) {
cout << fun::i << endl;
cout << fun::f(4) << endl;
cout << “Done” << endl;
return 1;
}

Just compile with g++ main.cpp defs.cpp.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s