First, a more abstract question. Is it good practice to use a namespace instead of a class, in terms of speed, when you don’t need a constructor/destructor or multiple copies of said object?
Second, I get ” ccEaV3B0.o:main.cc:(.text+0x10): undefined reference to `board::arbi’ ” when trying to include and use a namespace. I’m using Mingw32 on Windows 7, with the make command: g++ -Wall main.cc board.cc
This also happens when I compile seperately, using:
g++ -c board.cc
g++ -Wall main.cc board.o
Here are the (minimal) files:
main.cc:
#include <iostream>
using namespace std;
#include "board.h"
int main(){
cout << board::give() << endl;
return 0;
}
board.h:
#ifndef BOARD_H
#define BOARD_H
namespace board {
extern int arbi;
extern int give();
}
#endif
board.cc:
#include "board.h"
int board::give(){
return arbi;
}
Solved by giving an initialisation “int board::arbi = 5;” in board.cc
The question remains why you should use a class when something is clearly an object, even if you know there will always be exactly one instance of said object. It seems to me you would want globals, but to avoid name-clashing, you would put them in a namespace.
You need to define board::arbi in the board.cc file.
With the extern declaration you only comforted the compiler that you will provide the definition later, but you didn’t provide one.
Regarding the abstract question, the concept of class and namespace is very different. Class defines structure for objects which are ‘real’. i,e,they occupy memory. Namespace is just like a fence restricting the scope of global variables. They don’t occupy memory…. So, if you see logical objects in your program define them as classes. But, if you see only a set of global functions which are somehow related, but you can’t imagine them as a coherent object, use namespace.