I am never comfortable writing a header file, but I am trying to write from the net and try to understand
1 2 3 4 5 6 7 8 9
#ifndef Sample_h
#define Sample_h
namespace
{
int x;
int y;
void add(int , int);
}
#endif
1 2 3 4 5 6 7 8 9 10 11 12
#include "Sample_h.h"
#include<iostream>
usingnamespace std;
void add(int a, int b)
{
x = a+b;
y = a-b;
cout << "x" << x << endl ;
cout << "y" << y << endl;
}
But it's giving me error
[Linking error] undefined reference to '(anonymous namespace) :: add(int,int)'
And my another doubt is can we write the header file without the #macros i.r #ifndef or #define ?
You probably don't want to have the add function inside an anonymous namespace.
If you want the function add to be inside a namespace give the namespace a name by writing the name at the end of line 3 in Sample_h.h.
namespacefoo
Also add the namespace name before the function name, separated with :: when you define the function on line 5 in Sample_h.cpp.
voidfoo::add(int a, int b)
And do the same when you call the function in main.
foo::add(4,5);
#ifndef/#define/#endif prevents the content of the header from being included more than once. They are called include guards. http://en.wikipedia.org/wiki/Include_guard
By the way, avoid defining globals, especially in headers. The reason is that you'll come into issues with "duplicate names" which is a whole other barrel of worms. Instead use locals, especially in this situation. Drop the int x, and int y definitions in the headers and define it like so:
1 2 3 4 5 6 7
void add(int a, int b)
{
int x = a+b;
int y = a-b;
cout << "x" << x << endl ;
cout << "y" << y << endl;
}
To answer your last question: You don't need the #ifdef around a header, but the advantage is that it avoids errors when you include the headerfile recursively by accident, or include the same header twice.
Thanks for the reply but the problem that I was trying to solve is "Create a header file with an unnamed namespace . Include the header file in two separate cpp files and show that an unnamed space is unique for each translation unit.
How do I solve this then if I do not use the unnamed namespace?