📜  C / C++ #include指令和范例

📅  最后修改于: 2021-05-25 23:53:59             🧑  作者: Mango

#include是一种在程序中包含标准文件或用户定义文件的方法,并且大多写在任何C / C++程序的开头。该指令由预处理器读取,并命令其将用户定义的文件或系统头文件的内容插入以下程序。这些文件主要从外部源导入到当前程序中。导入可能是系统定义的或用户定义的此类文件的过程称为“文件包含” 。这种类型的预处理器指令告诉编译器在源代码程序中包含一个文件。以下是可以使用#include包含的两种文件类型:

  1. 头文件或标准文件:这是一个包含C / C++函数声明和宏定义的文件,这些声明将在多个源文件之间共享。诸如printf(),scanf(),cout,cin和各种其他输入输出或其他标准函数之类的函数包含在不同的头文件中。因此,要利用这些功能,用户需要导入一些定义所需功能的头文件。
  2. 用户定义的文件:这些文件类似于头文件,但它们是由用户自己编写和定义的。这样可以避免用户多次编写特定的函数。写入用户定义的文件后,可以使用#include预处理程序将其导入程序中的任何位置。

句法:

  1. #include "user-defined_file"

    包括使用“”:使用双引号(“”)时,预处理器将访问源“ header_file”所在的当前目录。此类型主要用于访问用户程序的任何头文件或用户定义的文件。

  2. #include 

    包括使用<>:在使用尖括号(<>)导入文件时,预处理器使用预定的目录路径来访问文件。它主要用于访问位于标准系统目录中的系统头文件。

示例1:这显示了系统I / O标头或标准文件的导入。

C
// C program showing the header file including
// standard input-output header file
  
#include 
  
int main()
{
  
    // "printf()" belongs to stdio.h
    printf("hello world");
    return 0;
}


C++
// C++ program showing the header file including
// standard input-output header file
  
#include 
using namespace std;
  
int main()
{
  
    // "cout" belongs to "iostream"
    cout << "hello world";
    return 0;
}


输出:
hello world

示例2:这显示了用户定义文件的创建和导入。

  1. 通过“ process.h”的名称创建用户定义的头。
    // It is not recommended to put function definitions
    // in a header file. Ideally there should be only
    // function declarations. Purpose of this code is
    // to only demonstrate working of header files.
      
    void add(int a, int b)
    {
        printf("Added value=%d\n", a + b);
    }
      
    void multiply(int a, int b)
    {
        printf("Multiplied value=%d\n", a * b);
    }
    
  2. 创建了包含上述“ process.h”的主文件。
    // C program to illustrate file inclusion
    // <> used to import system header file
    #include 
      
    // " " used to import user-defined file
    #include "process.h"
      
    // main function
    int main()
    {
        // add function defined in process.h
        add(10, 20);
      
        // mult function defined in process.h
        mult(10, 20);
      
        // printf defined in stdio.h
        printf("Process completed");
        return 0;
    }
    

解释:
将“ process.h”文件包含到另一个程序中。现在,由于我们需要将stdio.h包含在#include中,以便类似地使用printf()函数,因此,我们还需要将头文件process.h包含在#include“ process.h”中。 “”指示预处理程序查看当前文件夹或所有头文件的标准文件夹(如果在当前文件夹中找不到)。如果使用尖括号代替“”,则需要将其保存在头文件的标准文件夹中。如果使用“”,则需要确保将创建的头文件保存在与使用该头文件保存的当前C文件所在的文件夹中。

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”