C include windows linux

#include Директива (C/C++) #include directive (C/C++)

Указывает препроцессору включить содержимое указанного файла в точку, где отображается директива. Tells the preprocessor to include the contents of a specified file at the point where the directive appears.

Синтаксис Syntax

#include » путь — спецификация « #include « path-spec «
#include путь — спецификация > #include path-spec >

Примечания Remarks

Можно организовать константы и определения макросов в включаемые файлы (также известные как заголовочные файлы), а затем использовать #include директивы для добавления их в любой исходный файл. You can organize constant and macro definitions into include files (also known as header files) and then use #include directives to add them to any source file. Включаемые файлы также позволяют внедрять объявления внешних переменных и сложных типов данных. Include files are also useful for incorporating declarations of external variables and complex data types. Типы можно определять и именовать только один раз во включаемом файле, созданном с этой целью. The types may be defined and named only once in an include file created for that purpose.

Путь-Spec — это имя файла, которому при необходимости может предшествовать Спецификация каталога. The path-spec is a file name that may optionally be preceded by a directory specification. Имя файла должно указывать на существующий файл. The file name must name an existing file. Синтаксис инструкции path-Spec зависит от операционной системы, в которой компилируется программа. The syntax of the path-spec depends on the operating system on which the program is compiled.

Сведения о том, как ссылаться на сборки в приложении C++, скомпилированном с помощью /clr , см. в разделе #using директива. For information about how to reference assemblies in a C++ application that’s compiled by using /clr , see #using directive.

Обе синтаксические формы приводят к #include замене директивы всем содержимым указанного файла. Both syntax forms cause the #include directive to be replaced by the entire contents of the specified file. Различие между двумя формами — это порядок путей, которые препроцессор ищет при неполном указании пути. The difference between the two forms is the order of the paths that the preprocessor searches when the path is incompletely specified. В приведенной ниже таблице показывается различие между этими формами синтаксиса. The following table shows the difference between the two syntax forms.

Форма синтаксиса Syntax Form Действие Action
Форма в кавычках Quoted form Препроцессор ищет включаемые файлы в следующем порядке: The preprocessor searches for include files in this order:

1) в том же каталоге, что и файл, содержащий #include инструкцию. 1) In the same directory as the file that contains the #include statement.

2) в каталогах открытых в данный момент файлов включения в порядке, в котором они были открыты. 2) In the directories of the currently opened include files, in the reverse order in which they were opened. Поиск начинается в каталоге родительского включаемого файла, а затем выполняется в каталогах всех включаемых файлов-прародителей. The search begins in the directory of the parent include file and continues upward through the directories of any grandparent include files.

3) вдоль пути, указанного в каждом /I параметре компилятора. 3) Along the path that’s specified by each /I compiler option.

4) вдоль путей, указанных в INCLUDE переменной среды. 4) Along the paths that are specified by the INCLUDE environment variable.

Форма с угловыми скобками Angle-bracket form Препроцессор ищет включаемые файлы в следующем порядке: The preprocessor searches for include files in this order:

1) вдоль пути, указанного в каждом /I параметре компилятора. 1) Along the path that’s specified by each /I compiler option.

2) при компиляции происходит в командной строке вместе с путями, заданными INCLUDE переменной среды. 2) When compiling occurs on the command line, along the paths that are specified by the INCLUDE environment variable.

Как только препроцессор найдет файл с заданным именем, поиск останавливается. The preprocessor stops searching as soon as it finds a file that has the given name. При заключении полной, неоднозначной спецификации пути для включаемого файла между двойными кавычками ( » » ) препроцессор выполняет поиск только по этой спецификации пути и игнорирует стандартные каталоги. If you enclose a complete, unambiguous path specification for the include file between double quotation marks ( » » ), the preprocessor searches only that path specification and ignores the standard directories.

Если имя файла, заключенное в двойные кавычки, является неполным указанием пути, препроцессор сначала выполняет поиск в каталоге родительского файла. If the file name that’s enclosed in double quotation marks is an incomplete path specification, the preprocessor first searches the parent file’s directory. Родительский файл — это файл, содержащий #include директиву. A parent file is the file that contains the #include directive. Например, если включить файл с именем file2 в файл с именем file1, то файл file1 будет родительским. For example, if you include a file named file2 in a file named file1, file1 is the parent file.

Включаемые файлы могут быть вложенными: #include директива может находиться в файле с именем другой #include директивы. Include files can be nested: An #include directive can appear in a file that’s named by another #include directive. Например, file2 может включать файл3. For example, file2 could include file3. В этом случае file1 будет по-прежнему являться родителем file2, но это было бы бабушке файл3. In this case, file1 would still be the parent of file2, but it would be the grandparent of file3.

Если включаемые файлы являются вложенными и при компиляции происходит в командной строке, поиск в каталоге начинается в каталоге родительского файла. When include files are nested and when compiling occurs on the command line, directory searching begins in the directory of the parent file. Затем он переходит по каталогам всех файлов «бабушке». Then it proceeds through the directories of any grandparent files. Таким образом, поиск начинается относительно каталога, в котором находится исходный файл, обрабатываемый в текущий момент. That is, searching begins relative to the directory that contains the source that’s currently being processed. Если файл не найден, Поиск перемещается в каталоги, заданные параметром компилятора /I (дополнительные каталоги включаемых файлов) . If the file isn’t found, the search moves to directories that are specified by the /I (Additional include directories) compiler option. Наконец, выполняется поиск каталогов, заданных INCLUDE переменной среды. Finally, the directories that are specified by the INCLUDE environment variable are searched.

В среде разработки Visual Studio INCLUDE переменная среды игнорируется. Within the Visual Studio development environment, the INCLUDE environment variable is ignored. Вместо них используются значения, указанные в свойствах проекта для каталогов включения. The values specified in the project properties for include directories are used instead. Дополнительные сведения о настройке каталогов включения в Visual Studio см. в разделе включаемые каталоги и Дополнительные каталоги включения. For more information about how to set the include directories in Visual Studio, see Include Directories and Additional Include Directories.

В приведенном ниже примере демонстрируется включение файлов с помощью угловых скобок: This example shows file inclusion by using angle brackets:

В этом примере в исходную программу добавляется содержимое файла с именем stdio.h . The example adds the contents of the file named stdio.h to the source program. Угловые скобки приводят препроцессору для поиска в каталогах, заданных INCLUDE переменной среды для stdio.h , после того, как он выполняет поиск в каталогах, заданных /I параметром компилятора. The angle brackets cause the preprocessor to search the directories that are specified by the INCLUDE environment variable for stdio.h , after it searches directories that are specified by the /I compiler option.

В следующем примере демонстрируется включение файлов, заданных в кавычках: The next example shows file inclusion by using the quoted form:

В примере добавляется содержимое файла, указанного defs.h в исходной программе. The example adds the contents of the file that’s specified by defs.h to the source program. Кавычки означают, что препроцессор сначала попытается найти этот файл в каталоге, содержащем родительский исходный файл. The quotation marks mean that the preprocessor first searches the directory that contains the parent source file.

Для включаемых файлов поддерживается до 10 уровней вложения. Nesting of include files can continue up to 10 levels. После завершения обработки вложенного объекта #include препроцессор сохраняет вложенный родительский файл в исходный исходный файл. When processing of the nested #include is finished, the preprocessor continues to insert the enclosing parent include file into the original source file.

Только для систем Майкрософт Microsoft-specific

Чтобы найти исходные файлы для включения, препроцессор сначала выполняет поиск в каталогах, заданных /I параметром компилятора. To locate the source files to include, the preprocessor first searches the directories specified by the /I compiler option. Если /I параметр отсутствует или неисправен, препроцессор использует INCLUDE переменную среды для поиска всех включаемых файлов в угловых скобках. If the /I option isn’t present, or if it fails, the preprocessor uses the INCLUDE environment variable to find any include files within angle brackets. INCLUDE Переменная среды и /I параметр компилятора могут содержать несколько путей, разделенных точкой с запятой ( ; ). The INCLUDE environment variable and /I compiler option can contain multiple paths, separated by semicolons ( ; ). Если в качестве части /I параметра или переменной среды отображается несколько каталогов INCLUDE , препроцессор ищет их в том порядке, в котором они отображаются. If more than one directory appears as part of the /I option or within the INCLUDE environment variable, the preprocessor searches them in the order in which they appear.

Представим себе следующую команду: For example, the command

приводит к тому, что препроцессор ищет в каталоге D:\msvc\include\ включаемые файлы, например stdio.h . causes the preprocessor to search the directory D:\msvc\include\ for include files such as stdio.h . Ниже еще один пример: The commands

Эта инструкция действуют точно так же. have the same effect. Если найти файл в обоих наборах каталогов не удастся, возникает неустранимая ошибка компилятора. If both sets of searches fail, a fatal compiler error is generated.

Если имя файла указано полностью для включаемого файла с путем, содержащим двоеточие (например, F:\MSVC\SPECIAL\INCL\TEST.H ), препроцессор следует за путем. If the file name is fully specified for an include file that has a path that includes a colon (for example, F:\MSVC\SPECIAL\INCL\TEST.H ), the preprocessor follows the path.

Для включаемых файлов, указанных как #include «path-spec» , поиск по каталогу начинается в каталоге родительского файла, а затем продолжается через каталоги всех файлов бабушкх. For include files that are specified as #include «path-spec» , directory search begins in the directory of the parent file and then proceeds through the directories of any grandparent files. То есть поиск начинается относительно каталога, содержащего обрабатываемый исходный файл. That is, the search begins relative to the directory that contains the source file that’s being processed. Если файл «бабушке» отсутствует, и файл по-прежнему не найден, поиск продолжается так, как если бы имя файла было заключено в угловые скобки. If there’s no grandparent file and the file still isn’t found, the search continues as if the file name were enclosed in angle brackets.

КОНЕЦ Только для систем Майкрософт END Microsoft-specific

Взаимодействие Windows с Linux Windows interoperability with Linux

В подсистеме Windows для Linux (WSL) постоянно улучшается интеграция между Windows и Linux. The Windows Subsystem for Linux (WSL) is continuously improving integration between Windows and Linux. Можно сделать следующее. You can:

  • Запустить средства Windows (например, notepad.exe) из командной строки Linux (например, Ubuntu). Run Windows tools (ie. notepad.exe) from a Linux command line (ie. Ubuntu).
  • Запустить средства Linux (например, grep) из командной строки Windows (например, PowerShell). Run Linux tools (ie. grep) from a Windows command line (ie. PowerShell).
  • Совместное использование переменных среды между Linux и Windows. Share environment variables between Linux and Windows. (сборка 17063+) (Build 17063+)

Если вы используете Creators Update (октябрь 2017 г., сборка 16299) или Юбилейное обновление (август 2016 г., сборка 14393), перейдите к более ранним версиям Windows 10. If you’re running Creators Update (Oct 2017, Build 16299) or Anniversary Update (Aug 2016, Build 14393), jump to the Earlier versions of Windows 10.

Запуск инструментов Linux из командной строки Windows Run Linux tools from a Windows command line

Запускайте двоичные файлы Linux из командной строки Windows (CMD или PowerShell), используя wsl (или wsl.exe ). Run Linux binaries from the Windows Command Prompt (CMD) or PowerShell using wsl (or wsl.exe ).

Например: For example:

Двоичные файлы вызываются следующим образом. Binaries invoked in this way:

  • Используется тот же рабочий каталог, что и для текущей командной строки или сеанса PowerShell. Use the same working directory as the current CMD or PowerShell prompt.
  • Файл выполняется от имени пользователя WSL по умолчанию. Run as the WSL default user.
  • Требуются те же права администратора Windows, что и у вызывающего процесса и терминала. Have the same Windows administrative rights as the calling process and terminal.

Команда Linux после wsl (или wsl.exe ) обрабатывается как любая команда, выполняемая в WSL. The Linux command following wsl (or wsl.exe ) is handled like any command run in WSL. Можно выполнять sudo, конвейерную передачу и перенаправление файлов. Things such as sudo, piping, and file redirection work.

Пример использования sudo для обновления дистрибутива Linux по умолчанию: Example using sudo to update your default Linux distribution:

Имя пользователя дистрибутива Linux по умолчанию будет указано после выполнения этой команды, и вам будет предложено указать пароль. Your default Linux distribution user name will be listed after running this command and you will be asked for your password. После правильного ввода пароля дистрибутив скачает обновления. After entering your password correctly, your distribution will download updates.

Смешивание команд Linux и Windows Mixing Linux and Windows commands

Ниже приведено несколько примеров смешиваний команд Linux и Windows с помощью PowerShell. Here are a few examples of mixing Linux and Windows commands using PowerShell.

Чтобы выполнить команду Linux ls -la для вывода списка файлов и команду PowerShell findstr для фильтрации результатов слов, содержащих git, объедините команды: To use the Linux command ls -la to list files and the PowerShell command findstr to filter the results for words containing «git», combine the commands:

Чтобы выполнить команду PowerShell dir для вывода списка файлов и команду Linux grep для фильтрации результатов слов, содержащих git, объедините команды: To use the PowerShell command dir to list files and the Linux command grep to filter the results for words containing «git», combine the commands:

Чтобы использовать команду Linux ls -la для вывода списка файлов и команду PowerShell > out.txt для вывода этого списка в текстовый файл с именем out.txt, объедините команды: To use the Linux command ls -la to list files and the PowerShell command > out.txt to print that list to a text file named «out.txt», combine the commands:

Команды, передаваемые в wsl.exe , перенаправляются в процесс WSL без изменения. The commands passed into wsl.exe are forwarded to the WSL process without modification. Пути к файлам должны быть указаны в формате WSL. File paths must be specified in the WSL format.

Чтобы выполнить команду Linux ls -la для вывода списка файлов в пути файловой системы Linux /proc/cpuinfo с помощью PowerShell, сделайте следующее: To use the Linux command ls -la to list files in the /proc/cpuinfo Linux file system path, using PowerShell:

Чтобы выполнить команду Linux ls -la для вывода списка файлов в пути файловой системы Windows C:\Program Files с помощью PowerShell, сделайте следующее: To use the Linux command ls -la to list files in the C:\Program Files Windows file system path, using PowerShell:

Запуск инструментов Windows из Linux Run Windows tools from Linux

WSL может запускать средства Windows непосредственно из командной строки WSL с помощью [tool-name].exe . WSL can run Windows tools directly from the WSL command line using [tool-name].exe . Например, notepad.exe . For example, notepad.exe .

\’` as the file path.» Currently it I can just enter `notepad.exe foo.txt` and it seems to work fine, so explaining a situation where the file path is needed would be helpful. —>

Приложения, выполняемые таким образом, обладают следующими свойствами. Applications run this way have the following properties:

  • Рабочим каталогом остается каталог командной строки WSL (в большинстве случаев; исключения описаны ниже). Retain the working directory as the WSL command prompt (for the most part — exceptions are explained below).
  • Они имеют те же разрешения, что и процесс WSL. Have the same permission rights as the WSL process.
  • Они выполняются от имени активного пользователя Windows. Run as the active Windows user.
  • Они отображаются в диспетчере задач Windows так, как если бы они выполнялись непосредственно из командной строки. Appear in the Windows Task Manager as if directly executed from the CMD prompt.

Исполняемые файлы Windows, выполняемые в WSL, обрабатываются аналогично собственным исполняемым файлам Linux — конвейерной передаче, перенаправлению и даже фоновому режиму работы. Windows executables run in WSL are handled similarly to native Linux executables — piping, redirects, and even backgrounding work as expected.

Чтобы запустить средство Windows ipconfig.exe , использовать средство Linux grep для фильтрации результатов IPv4, а также средство Linux cut для удаления полей столбцов из дистрибутива Linux (например, Ubuntu), введите: To run the Windows tool ipconfig.exe , use the Linux tool grep to filter the «IPv4» results, and use the Linux tool cut to remove the column fields, from a Linux distribution (for example, Ubuntu) enter:

Давайте рассмотрим пример сочетания команд Windows и Linux. Let’s try an example mixing Windows and Linux commands. Откройте дистрибутив Linux (например, Ubuntu) и создайте текстовый файл: touch foo.txt . Open your Linux distribution (ie. Ubuntu) and create a text file: touch foo.txt . Теперь используйте команду Linux ls -la , чтобы отобразить список файлов прямого доступа и сведения об их создании, а также средство Windows PowerShell findstr.exe , чтобы отфильтровать результаты и отобразить только файл foo.txt : Now use the Linux command ls -la to list the direct files and their creation details, plus the Windows PowerShell tool findstr.exe to filter the results so only your foo.txt file shows in the results:

Средства Windows должны иметь расширение файла, его регистр символов должен совпадать с регистром в имени файла и эти файлы должны быть исполняемыми. Windows tools must include the file extension, match the file case, and be executable. Неисполняемые файлы, в том числе сценарии пакетного выполнения и Non-executables including batch scripts. собственные команды командной строки, такие как dir , можно выполнять с помощью команды cmd.exe /C . CMD native commands like dir can be run with cmd.exe /C command.

Например, отобразите список содержимого каталога C:\ файловой системы Windows, введя: For example, list the contents of your Windows files system C:\ directory, by entering:

Или выполните команду ping , чтобы отправить запрос проверки связи на веб-сайт microsoft.com: Or use the ping command to send an echo request to the microsoft.com website:

Параметры передаются в двоичный файл Windows без изменений. Parameters are passed to the Windows binary unmodified. Например, следующая команда откроет C:\temp\foo.txt в notepad.exe . As an example, the following command will open C:\temp\foo.txt in notepad.exe :

Этот способ также будет работать: This will also work:

Совместное использование переменных среды между Windows и WSL Share environment variables between Windows and WSL

Решение WSL и Windows совместно используют WSLENV — специальную переменную среды, созданную для взаимодействия Windows и дистрибутивов Linux, запущенных в WSL. WSL and Windows share a special environment variable, WSLENV , created to bridge Windows and Linux distributions running on WSL.

Свойства переменной WSLENV : Properties of WSLENV variable:

  • она используется совместно и существует в средах Windows и WSL; It is shared; it exists in both Windows and WSL environments.
  • это список переменных среды, которые совместно используют Windows и WSL; It is a list of environment variables to share between Windows and WSL.
  • она позволяет форматировать список переменных среды для корректного использования в Windows и WSL. It can format environment variables to work well in Windows and WSL.
  • она может использоваться в потоке между WSL и Win32. It can assist in the flow between WSL and Win32.

До выпуска сборки 17063 единственной переменной среды Windows,, к которой могла получить доступ WSL, была PATH (это позволяло запускать исполняемые файлы Win32 из WSL). Prior to 17063, only Windows environment variable that WSL could access was PATH (so you could launch Win32 executables from under WSL). Начиная со сборки 17063, WSLENV поддерживается. Starting in 17063, WSLENV begins being supported. WSLENV учитывает регистр. WSLENV is case sensitive.

Флаги WSLENV WSLENV flags

В WSLENV доступны четыре флага, влияющие на способ преобразования переменной среды. There are four flags available in WSLENV to influence how the environment variable is translated.

Флаги WSLENV : WSLENV flags:

  • /p преобразовывает пути WSL и Linux в пути Win32 и наоборот; /p — translates the path between WSL/Linux style paths and Win32 paths.
  • /l указывает, что переменная среды представляет собой список путей; /l — indicates the environment variable is a list of paths.
  • /u указывает, что эту переменную среды следует добавлять только при запуске WSL из Win32; /u — indicates that this environment variable should only be included when running WSL from Win32.
  • /w указывает, что эту переменную среды следует добавлять только при запуске Win32 из WSL. /w — indicates that this environment variable should only be included when running Win32 from WSL.

При необходимости флаги можно комбинировать. Flags can be combined as needed.

Узнайте больше о WSLENV, ознакомившись с часто задаваемыми вопросами и примерами установки значения WSLENV для объединения других предварительно определенных переменных среды с суффиксом в виде косой чертой и флагами для указания способа перевода значения и передачи переменных скрипту. Read more about WSLENV, including FAQs and examples of setting the value of WSLENV to a concatenation of other pre-defined environment vars, each suffixed with a slash followed by flags to specify how the value should be translated and passing variables with a script. В этой статье также показано, как настроить среду разработки с помощью языка программирования Go для совместного использования GOPATH с WSL и Win32. This article also includes an example for setting up a dev environment with the Go programming language, configured to share a GOPATH between WSL and Win32.

Отключение взаимодействия Disable interoperability

Пользователи могут отключить возможность запуска средств Windows для отдельного сеанса WSL, выполнив следующую команду в качестве привилегированного пользователя. Users may disable the ability to run Windows tools for a single WSL session by running the following command as root:

Чтобы повторно включить возможность запуска двоичных файлов Windows, закройте все сеансы WSL и повторно запустите bash.exe или выполните следующую команду от имени привилегированного пользователя. To re-enable Windows binaries, exit all WSL sessions and re-run bash.exe or run the following command as root:

Отключение взаимодействия не будет сохраняться между сеансами WSL, оно снова будет включено при запуске нового сеанса. Disabling interop will not persist between WSL sessions — interop will be enabled again when a new session is launched.

Предшествующие версии Windows 10 Earlier versions of Windows 10

В предшествующих версиях Windows 10 для команд взаимодействия существует несколько различий. There are several differences for the interoperability commands on earlier Windows 10 versions. Если вы используете версию Creators Update (октябрь 2017 г., сборка 16299) или Юбилейного обновления (август 2016 г., сборка 14393) Windows 10, мы рекомендуем выполнить обновление до последней версии Windows. Если это невозможно, мы выделили некоторые отличия при взаимодействии ниже. If you’re running a Creators Update (Oct 2017, Build 16299), or Anniversary Update (Aug 2016, Build 14393) version of Windows 10, we recommend you update to the latest Windows version, but if that’s not possible, we have outlined some of the interop differences below.

  • bash.exe заменен на wsl.exe ; bash.exe has been replaced with wsl.exe .
  • параметр -c не требуется для выполнения одной команды wsl.exe ; -c option for running a single command isn’t needed with wsl.exe .
  • путь Windows включен в переменную $PATH WSL. Windows path is included in the WSL $PATH .
  • Процесс отключения взаимодействия не изменяется. The process for disabling interop is unchanged.

Команды Linux можно запускать из командной строки Windows или из PowerShell, но для ранних версий Windows необходимо использовать команду bash . Linux commands can be run from the Windows Command Prompt or from PowerShell, but for early Windows versions, you man need to use the bash command. Например: For example:

Такие функции, как ввод, конвейерная передача и перенаправление файлов, работают должным образом. Things such as input, piping, and file redirection work as expected.

Команды WSL, передаваемые в bash -c , перенаправляются в процесс WSL без изменения. The WSL commands passed into bash -c are forwarded to the WSL process without modification. Пути к файлам должны быть указаны в формате WSL, кроме того, необходимо внимательно экранировать соответствующие знаки. File paths must be specified in the WSL format and care must be taken to escape relevant characters. Пример: Example:

При вызове средства Windows из дистрибутива WSL в ранних версиях Windows 10 необходимо указать путь к каталогу. When calling a Windows tool from a WSL distribution in an earlier version of Windows 10, you will need to specify the directory path. Например, в командной строке WSL введите: For example, from your WSL command line, enter:

В WSL эти исполняемые файлы обрабатываются аналогично собственным исполняемым файлам Linux. In WSL, these executables are handled similar to native Linux executables. Это означает, что добавление каталогов в путь Linux и их конвейерная передача между командами выполняется должным образом. This means adding directories to the Linux path and piping between commands works as expected. Например: For example:

Читайте также:  Режим электропитания максимальная производительность windows 10
Оцените статью