-5

I am an beginner in C++ language. I was able to understand the concept of header file , but facing the problem when i wanted to deal with them. I want to create a user-defined header files ? Expecting someone to show me a sample of it!

Thanks in advance,

Sunil
  • 11
  • 2
  • 3
    "*I was able to understand the concept of header file*" -- If you really understood, you'd never ask this question. Basically, just put your API declarations in a file and name it `.h` (or `.hpp`). –  Sep 06 '17 at 07:45
  • What do you mean exactly? How to create the file? What should go in there? Please be more specific. – Donald Duck Sep 07 '17 at 11:51

1 Answers1

2

A header is just a C source file that generally only contains:

  • Preprocessor #defines
  • Type declarations
  • Function declarations
  • Comments :)

There's nothing magical to it.

This could be a fully valid entire header:

// Save this as "adding.h"
int add_numbers(int a, int b);

It would be used like this:

In the file main.c:

#include "adding.h"

int main(void)
{
  const int x = 12;
  const int y = 27;
  printf("the sum of %d and %d is %d\n", x, y, add_numbers(x, y));
  return 0;
}

Then you'd of course also have adding.c:

#include "adding.h"
int add_numbers(int a, int b)
{
  return a + b;
}

--

Sometimes, in real projects, headers #include other headers, and that can create problems with repeated definitions (and also costs compilation time). To protect against that, include guards are often added. It would look like this:

// In "adding.h".
#if !defined ADDING_H_
#define ADDING_H_
int add_numbers(int a, int b);
#endif  // ADDING_H_

The contents of the header is just wrapped in an #if defined block, with a #define of the checked-for symbol inside it. This makes sure that multiple inclusions during the compilation of a single C file are harmless.

unwind
  • 391,730
  • 64
  • 469
  • 606