The concept and basic writing method of the header file in C + + _c language

Source: Internet
Author: User
Tags assert constant definition function definition

1 header files in the standard library
everything in the C + + standard library is placed in the name space STD (the content in the namespace is invisible to the outside), but a new problem has been created, and countless existing C + + code relies on the functionality in the pseudo-standard library that has been in use for years, such as the declaration in <iostream.h> The function in the header file, in order to be compatible with the STD packaging standard library that causes existing code to be unavailable, the standard board creates a new header file for the part of the standard library that wraps the STD, and the new header file has the same file name as the old one, except for the. h suffix, such as <iostream.h > has become <iostream>. For the C header file, the same method is used, but the character C is added to each header file name, such as the <string.h> becomes <cstring>,<stdio.h> becomes <cstdio>. It is best to use a new file header, a C + + program with a new header, to use a using namespace STD or using namespace std:: Specify the class name, and so on to make the required class visible to our code.

2 Custom header Files
to prevent header files from being repeatedly referenced, it is best to use preprocessing definitions, as follows:

#ifndef
The contents of the Myhead_h #define MYHEAD_H ...//header file
#endif

(1) #ifndef:
The indicator #ifndef is used to check whether the contents of the header file have been previously defined, and if so, the statement between #ifndef and #endif will not be executed. So it's customary to write the definition of the head file between the two statements.
For example: For MYHEAD.H this header file

#ifndef myhead_h
#define MYHEAD_H

#include "myhead.h" ...

#endif

(2) #ifdef
Indicator #ifdef is often used to determine whether a preprocessor constant has been defined to conditionally contain program code.
Such as:

 int main ()
 {
  #ifdef DEBUG
  cout<< "Beginning execution of main () \ n";
  #endif
  string Word;
  vector<string> text;
  while (Cin>>word)
  {
 #ifdef DEBUG
 cout<< Word read: <<word<< \ n;
 #endif
 text.push_back (word);
 //..... }

In this program, if debug is defined, the two statements contained therein are executed, and if not defined, two of the output statements are not executed.

3 Pretreatment related knowledge
(1) #ifdef: Determine whether a preprocessing constant is defined, such as #infef Degug
(2) #ifndef: Determine if a preprocessing constant is not defined
(3) #define: Define a preprocessing constant, such as #define DEBUG
(4) #include
(5) #endif
(6) The definition of a preprocessing constant can also be done at compile time, such as Cc–d DEBUG MAIN.C
(7) When compiling a C + + program, the compiler automatically defines a preprocessor name __cplusplus (note that there are two underscores in front), so you can determine whether the program is a C + + program to conditionally include some code, such as:

#ifndef myhead_h
#define MYHEAD_H
#ifdef __cplusplus
extern "C" {
#endif
int dmpostprocessing ();
#ifdef __cplusplus
}
#endif
#endif

(8) When compiling the C program, the compiler automatically defines the preprocessing constant __stdc__. Of course __cplusplus and __stdc__ are not defined at the same time;
(9) The other two more useful predefined constants are __line__ (the number of rows the record file has been compiled) and __file__ (containing the name of the file being compiled). Use the following:

if (element_count==0)
 cerr<< "Error:" <<__file__
   << ": Line" <<__line__
   < < "Element_count must be non-zero.\n";

(__date__): compilation date, compilation date of the current compiled file
(one) __time__: Compile time, compile time of the current compiled file
Format such as: HH:MM:SS

08:17:05 OCT 31 2006
The C + + name of the library header file is always preceded by the letter C, and the following is removed. h, such as assert.h in C + + for Cassert;

ASSERT () is a generic preprocessor macro provided in the C language standard library. It is often used to judge a necessary prerequisite so that the program can execute correctly. The header file associated with it is: #include <assert.h>
Such as:

 ASSERT (filename!=0);

said: If the following program can execute correctly, need filename is not 0, if the condition is false, that is, it is equal to 0, the assertion fails, the program will output diagnostic messages, and then terminate.

Its C + + name is: Cassert
C-Library header file's C + + name always starts with the letter C
Note: When using the header file in C-standard library, in C + +, be sure to use the using namespace Std to place it in a namespace to properly use

(13) in C + +, the header file suffix is different, so the standard C + + header file does not specify a suffix

4 file input and output in C + +

Header files: #include <fstream>

Use file Input Output instance:

 #include <fstream>
//In order to open an output file, first declare an object of Ofstream type:
 ofstream outfile ("Name-of-file");
To test whether a file has been successfully opened, the following is the judgment:
 //If the file cannot open a value of false
 if (!outfile)
   cerr<< sorry! We were unable to open the file!\n ";

To open an input file, first declare an object of type Ifstream:
  ifstream infile ("Name of File");
  if (!infile)
   cerr<< "sorry! We were unable to open the file!\n ";

A simple program:
  #include <iostream>
  #include <fstream>
  #include <string>

  int main ()
  {
   ofstream outfile ("Out_file");
 Ifstream infile ("In_file");
 if (!infile) {
   cerr<< "error:unable to open input file!\n";
   return-1;
 }
 if (!outfile) {
   cerr<< "error:unable to open output file!\n";
   return-2;
 }
 string Word;
 while (Infile>>word)
  outfile<<word<< ';
 return 0;
  }

What's in the header file?
the use of header files is mainly embodied in two aspects, one is heavy (sound chóng) used (that is, multiple use), the other is shared.

The header files that provide the standard library functions are for reuse. Many programs or projects may use these standard library functions, write them in the header file, each time you use only need to include the completed header file.

The common use of header files is mainly embodied in the multiple file structure of C + +. Since the current program is small, there is no need to use a multiple file structure, so the common use of this header file is not expanded. Interested readers can access the relevant books.
So, what should we write if we want to write a reusable header file ourselves?

Similar to the standard library function, we should give some functions or functions in the header file in a modular way. You should also include declarations of constants, variables, and types that implement these functions or functions independently.

Now let's look at an example of a header file application:

Shape.h #include "math.h"//the sine function is used to compute the Triangle Area const double pi=3.14159265358;//constant definition struct circle//type declaration {double r;};
struct square {double A;};
struct Rectangle {double a,b;};
struct triangle {double a,b,c,alpha,beta,gamma;}; Double perimeter_of_circle (double r)/function definition {return 2*pi*r.} double Area_of_circle (double R) {return pi*r*r;} DOUBL E Perimeter_of_square (Double a) {return 4*a.} double Area_of_square (double a) {return a*a;} double Perimeter_of_re Ctangle (double a,double b) {return 2* (a+b);} double Area_of_rectangle (double a,double b) {return a*b;} double Peri
Meter_of_triangle (double a,double b,double c) {return a+b+c;} double Area_of_triangle (double a,double b,double Gamma)
{return sin (gamma/180*pi) *A*B/2}
  Main.cpp #include "iostream.h" #include "shape.h"//contains our prepared shape.h int main () {Circle c={2};
  Square S={1};
  Rectangle r={2,3};
  Triangle t={3,4,5,36.86989,53.13011,90}; cout << "Perimeter of Circle" <<perimeteR_of_circle (C.R) <<endl;
  cout << "area of Square" <<area_of_square (S.A) <<endl;
  cout << "Perimeter of Rectangle" <<perimeter_of_rectangle (r.a,r.b) <<endl;
  cout << "area of Triangle" <<area_of_triangle (T.b,t.c,t.alpha) <<endl;
return 0;
 }

Run Result:

Perimeter of Circle 12.5664 area of
Square 1 Perimeter of rectangle an area of
Triangle 6

We have written the shape.h header file, later used to calculate the circumference or area of the graph, you do not need to rewrite the function, only need to include this header file on the line.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.