Talking about the role and usage of #ifndef, #define, #endif

The #ifndef.#define, #endif in the file are very important to avoid multiple inclusion. For example, if two C files include the same header file at the same time, there will be problems, so using this method can effectively avoid this situation.

General usage:

Take add.h as an example

#ifndef  _ADD_H_
#define _ADD_H_

//Include the class definition of add.h and the declaration of variables and functions here
For example, function declaration: int add(int a, int b); //semicolon must be added

#endif  //_ADD_H_

Write the add.cpp file

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

Main function main.cpp file

#include <iostream>
#include "add.h"
using namespace std;

intmain()
{    
    int a ;
    a = add(2,3);
    cout<<a<<endl;
    return 0;
}

1. In the program, _ADD_H_ is a preprocessor variable. The writing format is generally the header file name is capitalized, with underscores before and after, and "." is replaced with underscores. For example, stdio.h is represented as _STDIO_H_.

2. Preprocessor variables generally have two states: defined or undefined.

  The #ifndef directive checks if the specified preprocessor variable is undefined, if not, then all directives that follow are processed until #endif occurs; if it is defined, the #ifndef test is false, this directive and the #endif directive The code in between is ignored.

  The #define directive takes a name and defines that name as a preprocessor variable.

3. When calling the header file, generally use #include "add.h".

 

4. Use of header files:

  A header file is considered to be a standard header file if its name is enclosed in <>. The compiler will look for the header file in a predefined set of locations that can be modified by setting the lookup path environment variable or via command line options.

  If a header file name is enclosed in " ", it is considered a non-system file, and the search for non-system files usually starts at the path where the source file is located.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324713050&siteId=291194637