I’m working on a C++ project.
I had a class with its function, then I realized some of those functions weren’t related to that class but were just math functions so I decided to move them on to a namespace.
My first question is, what is the appropriate file extension for a c++ namespace?
I have a constants.h file where I plan on saving global constants, for example PI.
Right now:
#include <math.h>
const double PI = M_PI;
I have the namespace I talked about before, right now is called: specificMath.h
#include <stdlib.h>
#include "constants.h"
... more code
I have a gaussian.cpp:
#include "gaussian.h"
#include "specificMath.h"
#include <iostream>
... more code
This file includes a main function that right now does nothing, I just can’t get the whole project to compile without a main…
I have a gaussian.h where I’m not including anything, is that wrong?
A third class, which has no attributes, just methods (again, is this wrong? or not pretty?). truncatedFunctions.cpp
#include "specificMath.h"
#include <stdlib.h>
#include "truncatedFunctions.h"
#include "gaussian.h"
using namespace specificMath;
And its truncatedFunctions.h where, again, I’m not including anything.
And a fourth class where I include
#include "margin.h" //Its header, where I'm not including anything
#include "gaussian.h"
#include "specificMath.h"
using namespace specificMath;
When I “make” it, it seems to compile fine, but when it gets to the linking part I get A LOT of errors saying that things on my margin.cpp class were first defined in truncatedFunctions.cpp
I am going crazy. I have no idea why this is happening, or how to solve it. I would really appreciate if somebody could help me out, and please, any extra piece of advice would be great since I am really trying to learn as much as I can with this project. Thanks!
Did you define your functions in your specificMath.h? You should only declare those functions.
For example, if your specificMath.h contains function definitions like
and you are using including this file in several others, the linker is going crazy. Including means copying. And so you’ve got yourself
coolstuff::printdefined several times. The better way (and the only possible way when using self-written functions in many files) is splitting your code into a header and implementation as you did in gaussian.When you include coolstuff.namespace.h it will only declare functions. And you can declare the same function several times.
The .cpp file contains the implementation of your functions. Now your linker won’t get irritated because there is only one implementation of
coolstuff::printand not n (where n is the number of#include "cs.namespace.h"you used) ones.There is no standard namespace extension. Use .h/.cpp for header/implementation and a self-defined prefix, something like ‘nmspc’ or ‘nsc’. It’s up to you.