question?

someone can tell me why we write the #include<?????>in start of program usually.
why we don,t write it in any other part of source code?
when we use #include <filename> we are basically getting the source code from that file and putting it at the top, if the source code contains any functions they can then be used through-out the entire program.
C and C++ code is split into two parts: the interface (declarations) and the details (definitions).

As a simple example, suppose you have a function in "salutation.cc":
1
2
3
4
5
6
// salutation.cc
#include <iostream>

void hello( const char *name ) {
  std::cout << "Hello " << name << '.' << std::endl;
  }


You compile it, of course, with something like:

g++ -c salutation.cc

This gives you the "salutation.o" object file. Go ahead and delete the "salutation.cc" file.

Now say you want to use the function in the (already compiled) object file.
1
2
3
4
5
6
// hello.cc

int main() {
  hello( "Kaleem" );
  return 0;
  }

Compile with:

g++ -c hello.cc

Of course, the compiler tells you it has no idea what 'hello' is, since you never declared it.

We fix that by creating a "header file" which declares the function (tells the compiler what the function looks like).
1
2
3
4
5
6
7
8
// salutation.h

#ifndef SALUTATION_H
#define SALUTATION_H

void hello( const char *name );  // function prototype == declaration

#endif 

Now you can 'include' the file in "hello.cc":
1
2
3
4
5
6
7
8
// hello.cc

#include "salutation.h"

int main() {
  hello( "Kaleem" );
  return 0;
  }

And compile again:

g++ -c hello.cc

The compiler gets the file, and reads it as if it were:
1
2
3
4
5
6
void hello( const char *name );

int main() {
  hello( "Kaleem" );
  return 0;
  }

Compilation succeeds. Link and execute as normal:

g++ -o hello hello.o salutation.o
./hello

And you'll see:

Hello Kaleem.


The #include directive tells C++ that you want information about something. It can be functions or class declarations or #defines or all manner of stuff, except definitions --what belongs in .cpp files.

When you say
#include <iostream>
it tells the compiler that you are going to use the STL I/O classes. When you say
#include "salutation.h"
it tells the compiler that you are going to use your own stuff (in this example, a function).

Hope this helps.
Last edited on
thanx alot duoas!
i am new to programming would u please help me .
can you give some tutorial addresses that can help me
Topic archived. No new replies allowed.