- Системы сборки и проекты C/C++ в Visual Studio C/C++ projects and build systems in Visual Studio
- Компиляция C++ C++ compilation
- Набор инструментов MSVC The MSVC toolset
- Системы сборки и проекты Build systems and projects
- Использование MSBuild из командной строки MSBuild from the command line
- В этом разделе In This Section
- C and java compilation process in Windows
- 2 Answers 2
- The C compilation process
- Quick links
- What is meant by Compilation?
- The C compilation
- Pre-processing of source file
- Compilation of pre-processed file
- Assembling of compiled source code
- Linking of object files
- About Pankaj
Системы сборки и проекты C/C++ в Visual Studio C/C++ projects and build systems in Visual Studio
Visual Studio можно использовать для изменения, компиляции и сборки любой базы кода C++ с полной поддержкой IntelliSense без преобразования этого кода в проект Visual Studio или компиляции с помощью набора инструментов MSVC. You can use Visual Studio to edit, compile, and build any C++ code base with full IntelliSense support without having to convert that code into a Visual Studio project or compile with the MSVC toolset. Например, можно изменить кроссплатформенный проект CMake в Visual Studio на компьютере Windows, а затем скомпилировать его для Linux с помощью g++ на удаленном компьютере Linux. For example, you can edit a cross-platform CMake project in Visual Studio on a Windows machine, then compile it for Linux using g++ on a remote Linux machine.
Компиляция C++ C++ compilation
Сборка программы C++ — это компиляция исходного кода из одного или нескольких файлов и последующее связывание этих файлов в исполняемый файл (EXE), библиотеку динамической загрузки (DLL) или статическую библиотеку (LIB). To build a C++ program means to compile source code from one or more files and then link those files into an executable file (.exe), a dynamic-load library (.dll) or a static library (.lib).
Процесс базовой компиляции C++ состоит из трех основных этапов. Basic C++ compilation involves three main steps:
- Препроцессор C++ преобразует все определения #директив и макросов в каждом исходном файле. The C++ preprocessor transforms all the #directives and macro definitions in each source file. При этом создается единица трансляции . This creates a translation unit .
- Компилятор C++ компилирует каждую единицу трансляции в объектные файлы (OBJ), применяя заданные параметры компилятора. The C++ compiler compiles each translation unit into object files (.obj), applying whatever compiler options have been set.
- Компоновщик объединяет объектные файлы в один исполняемый файл, применяя заданные параметры компоновщика. The linker merges the object files into a single executable, applying the linker options that have been set.
Набор инструментов MSVC The MSVC toolset
В набор инструментов компилятора MSVC (также называемого цепочкой инструментов или средствами сборки) входят компилятор, компоновщик, стандартные библиотеки и связанные служебные программы Microsoft C++. The Microsoft C++ compiler, linker, standard libraries, and related utilities make up the MSVC compiler toolset (also called a toolchain or «build tools»). Они включены в состав в Visual Studio. These are included in Visual Studio. Этот набор инструментов можно скачать со страницы средств сборки для Visual Studio 2019 и использовать в качестве бесплатного автономного пакета. You can also download and use the toolset as a free standalone package from Build Tools for Visual Studio 2019 download.
Вы можете создавать простые программы, вызывая компилятор MSVC (cl.exe) непосредственно из командной строки. You can build simple programs by invoking the MSVC compiler (cl.exe) directly from the command line. Следующая команда принимает один файл исходного кода и вызывает cl.exe для создания исполняемого файла с именем hello.exe : The following command accepts a single source code file, and invokes cl.exe to build an executable called hello.exe :
Здесь компилятор (cl.exe) автоматически вызывает препроцессор и компоновщик C++ для создания окончательного выходного файла. Here the compiler (cl.exe) automatically invokes the C++ preprocessor and the linker to produce the final output file. Дополнительные сведения см. в статье Сборка из командной строки. For more information, see Building on the command line.
Системы сборки и проекты Build systems and projects
Большинство реальных программ используют некую систему сборки для управления сложностями компиляции нескольких исходных файлов для нескольких конфигураций (для отладки и выпуска), нескольких платформ (x86, x64, ARM и т. д.), настраиваемых шагов сборки и даже нескольких исполняемых файлов, которые должны быть скомпилированы в определенном порядке. Most real-world programs use some kind of build system to manage complexities of compiling multiple source files for multiple configurations (debug vs. release), multiple platforms (x86, x64, ARM, and so on), custom build steps, and even multiple executables that must be compiled in a certain order. Вы выполняете настройки в файле конфигурации сборки, а система сборки принимает этот файл в качестве входных данных перед вызовом компилятора. You make settings in a build configuration file(s), and the build system accepts that file as input before it invoke the compiler. Набор файлов исходного кода и файлов конфигурации сборки, необходимых для создания исполняемого файла, называется проектом . The set of source code files and build configuration files needed to build an executable file is called a project .
Далее приведены различные варианты для проектов Visual Studio — C++. The following list shows various options for Visual Studio Projects — C++:
Создайте проект Visual Studio с помощью интегрированной среды разработки Visual Studio и настройте его, используя страницы свойств. create a Visual Studio project by using the Visual Studio IDE and configure it by using property pages. Проекты Visual Studio создают программы, работающие в Windows. Visual Studio projects produce programs that run on Windows. Общие сведения см. в статье Компиляция и сборка в документации по Visual Studio. For an overview, see Compiling and Building in the Visual Studio documentation.
Откройте папку, содержащую файл CMakeLists.txt. open a folder that contains a CMakeLists.txt file. Поддержка CMake интегрирована в Visual Studio. CMake support is integrated into Visual Studio. Интегрированную среду разработки можно использовать для редактирования, тестирования и отладки без изменения файлов CMake. You can use the IDE to edit, test, and debug without modifying the CMake files in any way. При этом вы можете работать в том же проекте CMake, что и другие пользователи, которые могут использовать другие редакторы. This enables you to work in the same CMake project as others who might be using different editors. Поэтому CMake является рекомендуемым вариантом для кроссплатформенной разработки. CMake is the recommended approach for cross-platform development. Дополнительные сведения см. в статье Проекты CMake. For more information, see CMake projects.
Откройте свободную папку исходных файлов, где нет файла проекта. open a loose folder of source files with no project file. Для создания файлов в Visual Studio будет использоваться эвристика. Visual Studio will use heuristics to build the files. Это простой способ компиляции и запуска небольших консольных приложений. This is an easy way to compile and run small console applications. Дополнительные сведения см. в статье Проекты «Открыть папку» для C++. For more information, see Open Folder projects.
Откройте папку, содержащую файл makefile или любой другой файл конфигурации системы сборки. open a folder that contains a makefile, or any other build system configuration file. Вы можете настроить Visual Studio для вызова любых произвольных команд сборки, добавив файлы JSON в папку. You can configure Visual Studio to invoke any arbitrary build commands by adding JSON files to the folder. Дополнительные сведения см. в статье Проекты «Открыть папку» для C++. For more information, see Open Folder projects.
Откройте файл makefile Windows в Visual Studio. Open a Windows makefile in Visual Studio. Дополнительные сведения см. в разделе Справочник по программе NMAKE. For more information, see NMAKE Reference.
Использование MSBuild из командной строки MSBuild from the command line
Вы можете вызвать систему MSBuild из командной строки, передав ей VCXPROJ-файл вместе с параметрами командной строки. You can invoke MSBuild from the command line by passing it a .vcxproj file along with command-line options. Для реализации этого подхода требуется хорошее понимание MSBuild, а использовать его рекомендуется только в случае необходимости. This approach requires a good understanding of MSBuild, and is recommended only when necessary. Дополнительные сведения см. в разделе MSBuild. For more information, see MSBuild.
В этом разделе In This Section
Проекты Visual Studio Visual Studio projects
Создание, настройка и сборка проектов C++ в Visual Studio с помощью собственной системы сборки (MSBuild). How to create, configure, and build C++ projects in Visual Studio using its native build system (MSBuild).
Проекты CMake CMake projects
Создание, сборка и развертывание проектов CMake в Visual Studio. How to code, build, and deploy CMake projects in Visual Studio.
Проекты в виде папок Open Folder projects
Создание, сборка и развертывание проектов C++ в Visual Studio с помощью любой произвольной системы сборки или без нее. How to use Visual Studio to code, build, and deploy C++ projects based on any arbitrary build system, or no build system at all.
Сборки выпуска Release builds
Создание и устранение неполадок оптимизированных сборок выпуска для развертывания в системах конечных пользователей. How to create and troubleshoot optimized release builds for deployment to end users.
Использование набора инструментов MSVC из командной строки Use the MSVC toolset from the command line
Описание использования компилятора C/C++ и средств сборки непосредственно из командной строки, а не с помощью интегрированной среды разработки Visual Studio. Discusses how to use the C/C++ compiler and build tools directly from the command line rather than using the Visual Studio IDE.
Создание библиотек DLL в Visual Studio Building DLLs in Visual Studio
Создание, отладка и развертывание библиотек DLL (общих библиотек) C/C++ в Visual Studio. How to create, debug, and deploy C/C++ DLLs (shared libraries) in Visual Studio.
Создание изолированных приложений и параллельных сборок C/C++ Building C/C++ Isolated Applications and Side-by-side Assemblies
Описывает модель развертывания для классических приложений Windows, основанную на концепции изолированных приложений и параллельных сборок. Describes the deployment model for Windows Desktop applications, based on the idea of isolated applications and side-by-side assemblies.
Настройка проектов C++ для 64-разрядных целевых объектов с архитектурой x64 Configure C++ projects for 64-bit, x64 targets
Нацеливание на 64-разрядное оборудование с архитектурой x64 с использованием средств сборки MSVC. How to target 64-bit x64 hardware with the MSVC build tools.
Настройка проектов C++ для процессоров ARM Configure C++ projects for ARM processors
Нацеливание на оборудование ARM с использованием средств сборки MSVC. How to use the MSVC build tools to target ARM hardware.
Оптимизация кода Optimizing Your Code
Оптимизация кода различными способами, включая программную оптимизацию. How to optimize your code in various ways including program guided optimizations.
Настройка программ для Windows XP Configuring Programs for Windows XP
Нацеливание на Windows XP с использованием средств сборки MSVC. How to target Windows XP with the MSVC build tools.
Справочные сведения о построении C/C++ C/C++ Building Reference
Содержит ссылки на справочные статьи о сборке программ на C++, о параметрах компилятора и компоновщика, а также о различных средствах сборки. Provides links to reference articles about program building in C++, compiler and linker options, and various build tools.
C and java compilation process in Windows
What I know in Windows:
- file.C->gcc.exe->Assembly code->assembler of windows->file.O->link.exe->file.exe->CPU
- file.java->javac.exe=>file.class->java.exe=>Assembly code->assembler of windows->. (don’t know). ->. ->CPU
I’m really confused each time I seek for these processes could any one give me the details in C and java from source code to CPU in windows and giving names of programs such as compilers and assemblers
2 Answers 2
The Java virtual machine is called «virtual» because it is an abstract computer defined by a specification.
This tells us that there must be somehow a quite big difference between bytecode generated by a C compiler and/or the Java compiler.
If you are using e.g. gcc , as you already mentioned, the code is translated to assembly and then translated to binary by an assembler (let’s skip the Linker). These binary instructions are being loaded as you execute your .exe file. Windows reserves some physical pages for your process, sets up the virtual memory and starts to execute your program in userspace but without any detours.
The JVM on the other hand is a virtual computer in the sense that it «pretends» to be a machine on its own. This machine only understands the Java-Bytecode (yes, there is such a thing ah «Java-Assembly» too). But there is more. Because in order to actually work, the JVM has to execute that bytecode somehow on that «host machine. So the JVM has to interfere with the underlaying operating system and architecture. And this is what the JVM really does: It is a program that is written for some architectures and runs on some operating systems that pretends to be a «machine» in order to execute Java-Bytecode. This is what it makes «platform independent«.
Long story short:
Basically, there is happenning the «same» thing. Code gets translated to assembly, to binary and then gets executed on a «machine».
The C compilation process
Quick links
In the series of C tutorial we learned some basic of C programming language, configured C compiler and learned to compile and execute C program.
Since the compilation and execution of first C program, I must answer few questions before moving ahead. Questions such as — what is meant by compilation, what happens during compilation, how a simple plain text file gets converted to executable binary file.
In this post I will take a deep dive into the C compilation process. So let’s begin.
What is meant by Compilation?
The process of translating source code written in high level to low level machine code is called as Compilation. The compilation is done by a special software known as compiler. The compiler checks source code for any syntactical or structural errors and generates object code with extension .obj (in Windows) or .o (in Linux) if source code is error free.
Source code and executable code
The C compilation
The entire C compilation is broken to four stages.
The below image describes the entire C compilation process.
The C compilation process
To take a deep dive inside the C compilation process let’s compile a C program. Write or copy below C program and save it as compilation.c .
To compile the above program open command prompt and hit below command.
The -save-temps option will preserve and save all temporary files created during the C compilation. It will generate four files in the same directory namely.
Now lets look into these files and learn about different stages of compilation.
Pre-processing of source file
The C compilation begins with pre-processing of source file. Pre-processor is a small software that accepts C source file and performs below tasks.
- Remove comments from the source code.
- Macro expansion.
- Expansion of included header files.
After pre-processing it generates a temporary file with .i extension. Since, it inserts contents of header files to our source code file. Pre-processor generated file is larger than the original source file.
To view contents of the pre-processed file open .i in your favourite text editor. As in our case below is an extract of compilation.i file.
You can notice that the statement #include is replaced by its contents. Comment before the #include line is also trimmed.
Compilation of pre-processed file
In next phase of C compilation the compiler comes in action. It accepts temporary pre-processed .i file generated by the pre-processor and performs following tasks.
- Check C program for syntax errors.
- Translate the file into intermediate code i.e. in assembly language.
- Optionally optimize the translated code for better performance.
After compiling it generates an intermediate code in assembly language as file. It is assembly version of our source code.
Let us look into compilation.s file.
Assembling of compiled source code
Moving on to the next phase of compilation. Assembler accepts the compiled source code (compilation.s) and translates to low level machine code. After successful assembling it generates (in Linux) or (in Windows) file known as object file. In our case it generates the compilation.o file.
This file is encoded in low level machine language and cannot be viewed using text editors. However, if you still open this in notepad, it look like.
Linking of object files
Finally, the linker comes in action and performs the final task of compilation process. It accepts the intermediate file generated by the assembler. It links all the function calls with their original definition. Which means the function printf() gets linked to its original definition.
Linker generates the final executable file (.exe in windows).
Huuhh, these all happens in a blink by a software known as gcc .
report this ad
About Pankaj
Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves to learn new techs and write programming articles especially for beginners. He works at Vasudhaika Software Sols. as a Software Design Engineer and manages Codeforwin. In short Pankaj is Web developer, Blogger, Learner, Tech and Music lover.