Hello I'm trying to wrap my head around how namespace works. After reading about it I build a super simple program to test my understanding. Unfortunately I'm getting a multiple definition error and not sure why. Here is my program.
include <iostream>
include "file_one.cpp"
using namespace std;
int main()
{
int x = 2;
int y = 1;
cout << file_one::addNum(x,y);
}
* file_one.cpp
namespace file_one{
int addNum(int num1, int num2){ <<<** getting the error here**
int total;
total = num1 + num2;
return total;
}
}
You don't include file_one.cpp! That's another compilation unit that will be compiled before you call the function (must tell the compiler to compile that cpp file too). You have to have a header file add the declaration of function there. The compiler is yelling at you that there's already one function called file_one::addNum
So you will end up with something like this (3 files):
int main()
{
// your code...
}
namespace file_one
{
int add_num(int, int);
}
using namespace file_one;
int add_num(int a, int b)
{
// your code.
}
namespaces are essentially function grouping.
its there to prevent naming collisions.
now in practice it will requires working with header files and other CPP files which can get a bit confusing for beginnres.
I would post eamples but dude above me did a good job of it.