Include c что это

от admin

Препроцессор

Препроцессор является обязательным компонентом компилятора языка Си. Вообще весь процесс компиляции программы на языке Си разбивается на три этапа:

Препроцессор обрабатывает исходный текст программы до ее непосредственной компиляции. Результатом работы препроцессора является полный текст программы, который передается на компиляцию в исполняемый файл.

Затем компилятор компилирует обработанный препроцессором исходный код в объектные файлы.

И на последнем этапе линкер (линковщик) объединяет (линкует) объектные файлы в один исполняемый файл или файл динамической библиотеки.

Для управления препроцессором применяются директивы, каждая из которых начинается с символа решетки # и располагается на отдельной строке. Препроцессор просматривает текст программы, находит эти директивы и должным образом обрабатывает их.

Мы можем использовать следующие директивы:

#define : определяет макрос или препроцессорный идентификатор

#undef : отменяет определение макроса или идентификатора

#ifdef : проверяет, определен ли идентификатор

#ifndef : проверяет неопределенности идентификатор

#include : включает текст из файла

#if : проверяет условие выражение (как условная конструкция if)

#else : задает альтернативное условие для #if

#endif : окончание условной директивы #if

#elif : задает альтернативное условие для #if

#line : меняет номер следующей ниже строки

#error : формирует текст сообщения об ошибке трансляции

#pragma : определяет действия, которые зависят от конкретной реализации компилятора

# : пустая директива, по сути ничего не делает

Рассмотрим основные из этих директив.

Директива #include. Включение файлов

Ранее уже использовалась директива #include . Эта директива подключает в исходный текст файлы. Она имеет следующие формы применения:

Например, если нам надо задействовать в приложении консольный ввод-вывод с помощью функций printf() или scanf() , то нам надо подключить файл «stdio.h», который содержит определение этих функций:

При выполнении этой директивы препроцессор вставляет текст файла stdio.h . Данный файл еще называется заголовочным. Заголовочные файлы содержат прототипы функций, определения и описания типов и констант и имеют расширение .h .

Поиск файла производится стандартных системных каталогах. Вообще есть стандартный набор встроенных заголовочных файлов, который определяется стандартом языка и которые мы можем использовать:

assert.h : отвечает за диагностику программ

complex.h : для работы с комплексными числами

ctype.h : отвечает за преобразование и проверку символов

errno.h : отвечает за проверку ошибок

fenv.h : для доступа к окружению, которое управляет операциями с числами с плавающей точкой

float.h : отвечает за работу с числами с плавающей точкой

inttypes.h : для работы с большими целыми числами

iso646.h : содержит ряд определений, которые расширяют ряд логических операций

limits.h : содержит предельные значения целочисленных типов

locale.h : отвечает за работу с локальной культурой

math.h : для работы с математическими выражениями

setjmp.h : определяет возможности нелокальных переходов

signal.h : для обработки исключительных ситуаций

stdalign.h : для выравнивания типов

stdarg.h : обеспечивает поддержку переменного числа параметров

stdatomic.h : для выполнения атомарных операций по разделяемым данным между потоками

stdbool.h : для работы с типом _Bool

stddef.h : содержит ряд вспомогательных определений

stdint.h : для работы с целыми числами

stdio.h : для работы со средствами ввода-вывода

stdlib.h : содержит определения и прототипы функций общего пользования

stdnoreturn.h : содержит макрос noreturn

string.h : для работы со строками

tgmath.h : подключает math.h и complex.h плюс добавляет дополнительные возможности по работе с математическими вычислениями

threads.h : для работы с потоками

time.h : для работы с датами и временем

uchar.h : для работы с символами в кодировке Unicode

wchar.h : для работы с символами

wctype.h : содержит дополнительные возможности для работы с символами

Однако стоит отметить, что в различных средах к этому набору могут добавляться дополнительные встроенные заголовочные файлы для тех или иных целей, например, для работы с графикой.

Определение заголовочных файлов

Кроме стандартных заголовочных файлов мы можем подключать и свои файлы. Например, в той же папке, где находиться главный файл программы, определим еще один файл, который назовем numbers.c .

Определим в нем следующий код:

Здесь просто определена одна переменная. Теперь подключим этот файл в главный файл программы, который, допустим, называется app.c :

При подключении своих файлов их имя указывается в кавычках. И несмотря на то, что в программе не определена переменная number, она будет браться из подключенного файла numbers.c . Но опять же отмечу, важно, что в данном случае файл numbers.c располагается в одной папке с главным файлов программы.

Определение заголовочных файлов

В то же время данный способ прекрасно работает в GCC. Но для разных сред программирования способ подключения файлов может отличаться. Например, в Visual Studio мы получим ошибку. И более правильный подход будет состоять в том, что определить объявление объекта (переменной/константы) или функции в дополнительном заголовочном файле, а определение объекта или функции поместить в стандартный файл с расширением .c .

Например, в нашем в файле numbers.c уже есть определение переменной number. Теперь в ту же папку добавим новый файл numbers.h — файл с тем же названием, но другим расширением.

Подключение заголовочных файлов с помощью директивы include в программе на языке C

И определим в numbers.h следующий код:

Ключевое слово extern указывает, что данный объект является внешним. И в этом случае мы могли бы его подключить в файл исходного кода:

Далее чтобы скомпилировать эту программу, передадим компилятору GCC оба файла с исходным кодом — app.c и numbers.c :

Компилятору передаются файлы через пробел и компилируются в один исполняемый файл.

Примечание для Visual Studio

Если разработка ведется в Visual Studio , то не надо подключать файл с исходным кодом ( numbers.c ), однако чтобы Visual Studio видела функционал файла в процессе разработки, может потребоваться подключить заголовочный файл ( numbers.h ). При этом заголовочный файл numbers.h помещается в папку Headers Files .

2. Header Files

A header file is a file containing C declarations and macro definitions (see section 3. Macros) to be shared between several source files. You request the use of a header file in your program by including it, with the C preprocessing directive `#include’ .

Header files serve two purposes.


    System header files declare the interfaces to parts of the operating system. You include them in your program to supply the definitions and declarations you need to invoke system calls and libraries.

Including a header file produces the same results as copying the header file into each source file that needs it. Such copying would be time-consuming and error-prone. With a header file, the related declarations appear in only one place. If they need to be changed, they can be changed in one place, and programs that include the header file will automatically use the new version when next recompiled. The header file eliminates the labor of finding and changing all the copies as well as the risk that a failure to find one copy will result in inconsistencies within a program.

In C, the usual convention is to give header files names that end with `.h’ . It is most portable to use only letters, digits, dashes, and underscores in header file names, and at most one dot.

2.1 Include Syntax

Both user and system header files are included using the preprocessing directive `#include’ . It has two variants:

#include < file > This variant is used for system header files. It searches for a file named file in a standard list of system directories. You can prepend directories to this list with the `-I’ option (see section 12. Invocation).

#include » file » This variant is used for header files of your own program. It searches for a file named file first in the directory containing the current file, then in the same directories used for < file > .

The argument of `#include’ , whether delimited with quote marks or angle brackets, behaves like a string constant in that comments are not recognized, and macro names are not expanded. Thus, #include <x/*y> specifies inclusion of a system header file named `x/*y’ .

However, if backslashes occur within file , they are considered ordinary text characters, not escape characters. None of the character escape sequences appropriate to string constants in C are processed. Thus, #include «x\n\\y» specifies a filename containing three backslashes. (Some systems interpret `\’ as a pathname separator. All of these also interpret `/’ the same way. It is most portable to use only `/’ .)

It is an error if there is anything (other than comments) on the line after the file name.

2.2 Include Operation

The `#include’ directive works by directing the C preprocessor to scan the specified file as input before continuing with the rest of the current file. The output from the preprocessor contains the output already generated, followed by the output resulting from the included file, followed by the output that comes from the text after the `#include’ directive. For example, if you have a header file `header.h’ as follows,

and a main program called `program.c’ that uses the header file, like this,

the compiler will see the same token stream as it would if `program.c’ read

Included files are not limited to declarations and macro definitions; those are merely the typical uses. Any fragment of a C program can be included from another file. The include file could even contain the beginning of a statement that is concluded in the containing file, or the end of a statement that was started in the including file. However, a comment or a string or character constant may not start in the included file and finish in the including file. An unterminated comment, string constant or character constant in an included file is considered to end (with an error message) at the end of the file.

To avoid confusion, it is best if header files contain only complete syntactic units—function declarations or definitions, type declarations, etc.

The line following the `#include’ directive is always treated as a separate line by the C preprocessor, even if the included file lacks a final newline.

2.3 Search Path

GCC looks in several different places for headers. On a normal Unix system, if you do not instruct it otherwise, it will look for headers requested with #include < file > in:

For C++ programs, it will also look in `/usr/include/g++-v3′ , first. In the above, target is the canonical name of the system GCC was configured to compile code for; often but not always the same as the canonical name of the system it runs on. version is the version of GCC in use.

You can add to this list with the `-I dir ‘ command line option. All the directories named by `-I’ are searched, in left-to-right order, before the default directories. You can also prevent GCC from searching any of the default directories with the `-nostdinc’ option. This is useful when you are compiling an operating system kernel or some other program that does not use the standard C library facilities, or the standard C library itself.

GCC looks for headers requested with #include » file » first in the directory containing the current file, then in the same places it would have looked for a header requested with angle brackets. For example, if `/usr/include/sys/stat.h’ contains #include «types.h» , GCC looks for `types.h’ first in `/usr/include/sys’ , then in its usual search path.

`#line’ (see section 6. Line Control) does not change GCC’s idea of the directory containing the current file.

You may put `-I-‘ at any point in your list of `-I’ options. This has two effects. First, directories appearing before the `-I-‘ in the list are searched only for headers requested with quote marks. Directories after `-I-‘ are searched for all headers. Second, the directory containing the current file is not searched for anything, unless it happens to be one of the directories named by an `-I’ switch.

`-I. -I-‘ is not the same as no `-I’ options at all, and does not cause the same behavior for `<>’ includes that `»»‘ includes get with no special options. `-I.’ searches the compiler’s current working directory for header files. That may or may not be the same as the directory containing the current file.

If you need to look for headers in a directory named `-‘ , write `-I./-‘ .

There are several more ways to adjust the header search path. They are generally less useful. See section 12. Invocation.

2.4 Once-Only Headers

If a header file happens to be included twice, the compiler will process its contents twice. This is very likely to cause an error, e.g. when the compiler sees the same structure definition twice. Even if it does not, it will certainly waste time.

The standard way to prevent this is to enclose the entire real contents of the file in a conditional, like this:

This construct is commonly known as a wrapper #ifndef . When the header is included again, the conditional will be false, because FILE_FOO_SEEN is defined. The preprocessor will skip over the entire contents of the file, and the compiler will not see it twice.

GNU CPP optimizes even further. It remembers when a header file has a wrapper `#ifndef’ . If a subsequent `#include’ specifies that header, and the macro in the `#ifndef’ is still defined, it does not bother to rescan the file at all.

You can put comments outside the wrapper. They will not interfere with this optimization.

The macro FILE_FOO_SEEN is called the controlling macro or guard macro . In a user header file, the macro name should not begin with `_’ . In a system header file, it should begin with `__’ to avoid conflicts with user programs. In any kind of header file, the macro name should contain the name of the file and some additional text, to avoid conflicts with other header files.

2.5 Computed Includes

Sometimes it is necessary to select one of several different header files to be included into your program. They might specify configuration parameters to be used on different sorts of operating systems, for instance. You could do this with a series of conditionals,

That rapidly becomes tedious. Instead, the preprocessor offers the ability to use a macro for the header name. This is called a computed include . Instead of writing a header name as the direct argument of `#include’ , you simply put a macro name there instead:

SYSTEM_H will be expanded, and the preprocessor will look for `system_1.h’ as if the `#include’ had been written that way originally. SYSTEM_H could be defined by your Makefile with a `-D’ option.

You must be careful when you define the macro. `#define’ saves tokens, not text. The preprocessor has no way of knowing that the macro will be used as the argument of `#include’ , so it generates ordinary tokens, not a header name. This is unlikely to cause problems if you use double-quote includes, which are close enough to string constants. If you use angle brackets, however, you may have trouble.

The syntax of a computed include is actually a bit more general than the above. If the first non-whitespace character after `#include’ is not `»‘ or `<’ , then the entire line is macro-expanded like running text would be.

If the line expands to a single string constant, the contents of that string constant are the file to be included. CPP does not re-examine the string for embedded quotes, but neither does it process backslash escapes in the string. Therefore

looks for a file named `a\»b’ . CPP searches for the file according to the rules for double-quoted includes.

If the line expands to a token stream beginning with a `<’ token and including a `>’ token, then the tokens between the `<’ and the first `>’ are combined to form the filename to be included. Any whitespace between tokens is reduced to a single space; then any space after the initial `<’ is retained, but a trailing space before the closing `>’ is ignored. CPP searches for the file according to the rules for angle-bracket includes.

In either case, if there are any tokens on the line after the file name, an error occurs and the directive is not processed. It is also an error if the result of expansion does not match either of the two expected forms.

These rules are implementation-defined behavior according to the C standard. To minimize the risk of different compilers interpreting your computed includes differently, we recommend you use only a single object-like macro which expands to a string constant. This will also minimize confusion for people reading your program.

2.6 Wrapper Headers

Sometimes it is necessary to adjust the contents of a system-provided header file without editing it directly. GCC’s fixincludes operation does this, for example. One way to do that would be to create a new header file with the same name and insert it in the search path before the original header. That works fine as long as you’re willing to replace the old header entirely. But what if you want to refer to the old header from the new one?

You cannot simply include the old header with `#include’ . That will start from the beginning, and find your new header again. If your header is not protected from multiple inclusion (see section 2.4 Once-Only Headers), it will recurse infinitely and cause a fatal error.

You could include the old header with an absolute pathname: This works, but is not clean; should the system headers ever move, you would have to edit the new headers to match.

There is no way to solve this problem within the C standard, but you can use the GNU extension `#include_next’ . It means, «Include the next file with this name.» This directive works like `#include’ except in searching for the specified file: it starts searching the list of header file directories after the directory in which the current file was found.

Suppose you specify `-I /usr/local/include’ , and the list of directories to search also includes `/usr/include’ ; and suppose both directories contain `signal.h’ . Ordinary #include <signal.h> finds the file under `/usr/local/include’ . If that file contains #include_next <signal.h> , it starts searching after that directory, and finds the file in `/usr/include’ .

`#include_next’ does not distinguish between < file > and » file » inclusion, nor does it check that the file you specify has the same name as the current file. It simply looks for the file named, starting with the directory in the search path after the one where the current file was found.

The use of `#include_next’ can lead to great confusion. We recommend it be used only when there is no other alternative. In particular, it should not be used in the headers belonging to a specific program; it should be used only to make global corrections along the lines of fixincludes .

2.7 System Headers

The header files declaring interfaces to the operating system and runtime libraries often cannot be written in strictly conforming C. Therefore, GCC gives code found in system headers special treatment. All warnings, other than those generated by `#warning’ (see section 5. Diagnostics), are suppressed while GCC is processing a system header. Macros defined in a system header are immune to a few warnings wherever they are expanded. This immunity is granted on an ad-hoc basis, when we find that a warning generates lots of false positives because of code in macros defined in system headers.

Normally, only the headers found in specific directories are considered system headers. These directories are determined when GCC is compiled. There are, however, two ways to make normal headers into system headers.

The `-isystem’ command line option adds its argument to the list of directories to search for headers, just like `-I’ . Any headers found in that directory will be considered system headers.

All directories named by `-isystem’ are searched after all directories named by `-I’ , no matter what their order was on the command line. If the same directory is named by both `-I’ and `-isystem’ , `-I’ wins; it is as if the `-isystem’ option had never been specified at all.

There is also a directive, #pragma GCC system_header , which tells GCC to consider the rest of the current include file a system header, no matter where it was found. Code that comes before the `#pragma’ in the file will not be affected. #pragma GCC system_header has no effect in the primary source file.

On very old systems, some of the pre-defined system header directories get even more special treatment. GNU C++ considers code in headers found in those directories to be surrounded by an extern «C» block. There is no way to request this behavior with a `#pragma’ , or from the command line.

What does #include actually do?

In C (or a language based on C), one can happily use this statement:

And voila, every function and variable in hello.h is automagically usable.

But what does it actually do? I looked through compiler docs and tutorials and spent some time searching online, but the only impression I could form about the magical #include command is that it «copy pastes» the contents of hello.h instead of that line. There’s gotta be more than that.

6 Answers 6

Logically, that copy/paste is exactly what happens. I’m afraid there isn’t any more to it. You don’t need the ; , though.

Your specific example is covered by the spec, section 6.10.2 Source file inclusion, paragraph 3:

A preprocessing directive of the form

# include » q-char-sequence » new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the » delimiters.

That (copy/paste) is exactly what #include «header.h» does.

Note that it will be different for #include <header.h> or when the compiler can’t find the file «header.h» and it tries to #include <header.h> instead.

Not really, no. The compiler saves the original file descriptor on a stack and opens the #include d file; when it reaches the end of that file, it closes it and pops back to the original file descriptor. That way, it can nest #include d files almost arbitrarily.

The # include statement "grabs the attention" of the pre-processor (the process that occurs before your program is actually compiled) and "tells" the pre-processor to include whatever follows the # include statement.

While the pre-processor can be told to do quite a bit, in this instance it’s being asked to recognize a header file (which is denoted with a .h following the name of that header, indicating that it’s a header).

Now, a header is a file containing C declarations and definitions of functions not explicitly defined in your code. What does this mean? Well, if you want to use a function or define a special type of variable, and you know that these functions/definition are defined elsewhere (say, the standard library), you can just include ( # include ) the header that you know contains what you need. Otherwise, every time you wanted to use a print function (like in your case), you’d have to recreate the print function.

If its not explicitly defined in your code and you don’t #include the header file with the function you’re using, your compiler will complain saying something like: "Hey! I don’t see where this function is defined, so I don’t know what to with this undefined function in your code!".

#define and #include in C

All the statements starting with # (hash) symbol are known as preprocessor directives/commands therefore, #define and #include are also known as preprocessor directives. Preprocessor directives are executed before any other command in our program. In a C Program, we generally write all the preprocessor directives outside the main() function at the top of our C program. The #define directive is used to define constants or an expression in our C Program, while #include directive is used to include the content of header files in our C program.

Scope

  • This article is an introduction to the preprocessor directives like #define and #include .
  • This article contains definitions, syntax and examples of #define and #include directives.

Introduction

There are three major types of preprocessor directives that are used in a C program: macros , file inclusion , conditional compilation .

Macros

It is some constant value or an expression that can be defined using the #define command in our C Program. Examples :

    Defining a value

file inclusion

It is adding defined as content of a header file into our C Program, and it can be done using the #include command. Examples :

    Including standard input output header file

conditional compilation

It is running or skipping a piece of code at some macros condition (a constant value or an expression defined using #define), and it can be performed using commands like #ifdef , #endif , #ifndef , #if , #else and #elif in a C Program. Example :

    printing age if macro is defined, else printing not defined

Output :

Now, To understand how and why preprocessor directives are executed before compilation, let us look at the process of how the whole compilation process works in a C Program.

Let's suppose we have written a hello.c program to print Hello, World! in the output. The compilation process will generate an executable file, hello.exe from our hello.c program file.

Compilation Process

It is a process of converting Human Understandable (High Level) Code into Machine Understandable (Low Level) Code. Let us look at the steps involved in the compilation process.

  • Step 1, We have a written C Program file with an extension of .c i.e. hello.c file.
  • Step 2 is preprocessing of header files, all the statements starting with # (hash symbol) are replaced during the compilation process with the help of a pre-processor. It generates an intermediate file with .i file extension i.e. a hello.i file.
  • Step 3 is a compilation of hello.i file, compiler software translates the hello.i file to hello.s file having assembly-level instructions (low-level code).
  • Step 4, assembly-level code instructions are converted into a machine-understandable code (binary/hexadecimal form) by the assembler, and the file generated is known as the object file with an extension of .obj i.e. hello.obj file.
  • Step 5, Linker is used to link the library files with the object file to define the unknown statements. It generates an executable file with .exe extension i.e. a hello.exe file.
  • Next, we can run the hello.exe executable file to get the desired output on our output window.

The below diagram shows all the steps involved in the compilation process.

Now, let us see the definitions, syntax, and examples of #define and #include.

What is #define in C?

  • #define is a preprocessor directive that is used to define macros in a C program.
  • #define is also known as a macros directive.
  • #define directive is used to declare some constant values or an expression with a name that can be used throughout our C program.
  • Whenever a #define directive is encountered, the defined macros name replaces it with some defined constant value or an expression.

What is #include in C?

  • #include is a preprocessor directive that is used for file inclusion in a C program.
  • #include is also known as a file inclusion directive.
  • #include directive is used to add the content/piece of code from a reserved header file into our code file before the compilation of our C program.
  • These header files include definitions of many pre-defined functions like printf() , scanf() , getch() , etc.

Syntax of #define in C

CNAME : Name of the constant value or the expression. Generally, programmers define it in uppercase letters but it is not necessary like LIMIT , AREA(l,b) , etc.

value : It can be any constant value and can be of any data type int , char , float , string etc.

expression: It can be any piece of code or any mathematical expression like (length * breadth) , (a * a) , etc.

Example Syntax :

Note : #define directive doesn't require a ; (semi-colon) at the end of the statement.

Syntax of #include in C

filename : It is the header file name that is required in our C Program.

Example Syntax :

Examples of #define in C

We will see two examples of #define , first with a constant value and second with an expression.

Area of a circle using #define CNAME value.

We are defining the value of PI to be 3.14 in the below example using the #define directive, we are using the PI value in calculating the area of circle i.e. PI * r * r .

C Program :

Custom Input :

Output :

You can run and check your code here.

Explanation :

  • We have included a standard input output header file using the #include <stdio.h> directive.
  • We have defined the value of PI to be 3.14 using the #define directive.
  • In the main() function, we are using an input float variable radius and an area variable to store the area value.
  • area = PI * radius * radius , in this statement, PI is replaced by 3.14 as we have defined it using the #define command.
  • printf("\nArea of Circle : %0.2f", area); will print the area of circle with precision of 2 decimal places.
  • return 0; will exit the program successfully.

Square of a given number using #define CNAME expression.

We are defining a mathematical expression (a * a) to the cname SQR(a) to calculate the square of a number using the #define directive.

Читать:
Surfeasy vpn как пользоваться

Похожие статьи