Help with header file

Hi All,

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>
using namespace std;

void add(int a, int b)
{
     x = a+b;
     y = a-b;
     cout << "x" << x << endl ;
     cout << "y" << y << endl;
}


1
2
3
4
5
6
7
8
9
10
11
#include "Sample_h.h"
#include <iostream>

using namespace std;

int main()
{
    add(4,5);
    system("pause");
    return 0;
}

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.
 
namespace foo
Also add the namespace name before the function name, separated with :: when you define the function on line 5 in Sample_h.cpp.
 
void foo::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
You can do one of two things:

First, name and use the namespace:
1
2
3
4
5
6
7
8
9
#ifndef Sample_h
#define Sample_h
namespace ns
{
         int x;
         int y;
         void add(int , int);
}
#endif 

then
1
2
3
4
5
int main()
{
    ns::add(4,5);
    ...
}


The other suggestion is to just remove the namespace:
1
2
3
4
5
6
#ifndef Sample_h
#define Sample_h

void add(int , int);

#endif  


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.
Last edited on
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?
Well, in that case I think you should just move the declaration of add outside the namespace and leave x and y where they are.
Topic archived. No new replies allowed.