Reputation: 169
My goal is to declare an existing function from function.cpp
in a namespace, so I can avoid name duplicates. I do not want to define the function inside the namespace, but on a seperate file (in this case function.cpp
). I created the following example to represent my effort in the case.
I am new to C++ and I am probably doing something wrong in the definitions, and unfortunately I don't seem to find the problem. Any help would be greatly appreciated.
//Header.h
int adder(int a, int b);
//Function.cpp
#include "Header.h"
int adder(int a, int b) {
return (a + b);
}
//Namespace.h
#include "Header.h"
namespace orange {
int adder(int a, int b);
}
//Main.cpp
#include <iostream>
#include "Namespace.h"
using namespace orange;
int main() {
std::cout << orange::adder(7, 5) << "\n";
}
Upvotes: 0
Views: 887
Reputation: 133
The problem is here.
using namespace orange;
You've included "Namespace.h"
, which contains already "Header.h"
, so in your Main.cpp file you actually have
int adder(int a, int b);
namespace orange {
int adder(int a, int b);
}
This is totally fine, you can have function with the same name in different namespaces, the first one is in the global namespace, and the second one is in the orange
namespace.
When you say using namespace orange;
you bring everything from orange namespace you have in that file to the global namespace, and now, you basically have two int adder(int a, int b);
in the same place.
When you try to call that function, compiler is confused, he can call both, and doesn't know which one you actually want.
To overcome this problem you shouldn't use using namespace orange;
, but in the actual call specify which function you want to call, if the global one, then just call
std::cout << adder(7, 5) << "\n";
If function defined in the orange
namespace, call this way
std::cout << orange::adder(7, 5) << "\n";
Upvotes: 1