Как установить компилятор gcc / g++ для windows. установка gcc

Install MinGW-w64

MinGW-w64 comprises development tools for compiling and debugging.
Download the Mingw-w64 Installer from here and follow the steps in the wizard.
It is essential that the installation path does not contain any spaces.
Therefore, you cannot install MinGW-w64 in Program Files.
We recommend to create a folder mingw-w64 on your system drive (e.g., C:\mingw).
Install a current version and specify win32 as thread when requested.
Additionally, choose the architecture x86_64.

After installing, you need to edit the PATH variable.
You can access the System Control Center by pressing Windows Key + Pause.
In the System window, click Advanced System Settings → Advanced (tab) → Environment Variables.
For Windows 10, a quick access is to enter «Edit the system environment variables» in the Start Search of Windows and click the button «Environment Variables».
Change the PATH variable (double-click on it or Select and Edit), and add the path where your MinGW-w64 has been installed to e.g., C:\mingw\mingw64\bin.
This folder should contain a number of .exe-files that you can see in your Explorer.

Install Required Cygwin Packages

Next, you’ll need to add several packages to Cygwin. You can add them all in one fell swoop. Just open a Command Prompt (in Windows), navigate to the folder where the Cygwin installer is located, and run the following command:

A window will pop up and download all the required packages along with their dependencies.

At this point, you now have a working GCC compiler on your system. It’s not the latest version of GCC; it’s whatever version the Cygwin maintainers chose as their system compiler. At the time of writing, that’s GCC 4.8.3. To get a more recent version of GCC, you’ll have to compile it yourself, using the GCC compiler you already have.

The Build

We build a toolset running on your host that can turn source code into object files for your target system.

You need to decide where to install your new compiler. It is dangerous and a very bad idea to install it into system directories. You also need to decide whether the new compiler should be installed globally or just for you. If you want to install it just for you (recommended), installing into $HOME/opt/cross is normally a good idea. If you want to install it globally, installing it into /usr/local/cross is normally a good idea.

Please note that we build everything out of the source directory tree, as is considered good practice. Some packages only support building outside, some only inside and some both (but may not offer extensive checking with make). Building GCC inside the source directory tree fails miserably, at least for older versions.

Preparation

export PREFIX="$HOME/opt/cross"
export TARGET=i686-elf
export PATH="$PREFIX/bin:$PATH"

We add the installation prefix to the PATH of the current shell session. This ensures that the compiler build is able to detect our new binutils once we have built them.

The prefix will configure the build process so that all the files of your cross-compiler environment end up in $HOME/opt/cross. You can change that prefix to whatever you like (e.g., /opt/cross or $HOME/cross would be options). If you have administrator access and wish to make the cross-compiler toolchain available to all users, you can install it into the /usr/local prefix — or perhaps a /usr/local/cross prefix if you are willing to change the system configuration such that this directory is in the search paths for all users. Technically, you could even install directly to /usr, so that your cross-compiler would reside alongside your system compiler, but that is not recommended for several reasons (like risking to overwrite your system compiler if you get TARGET wrong, or getting into conflict with your system’s package management).

Binutils

cd $HOMEsrc
 
mkdir build-binutils
cd build-binutils
..binutils-x.y.zconfigure --target=$TARGET --prefix="$PREFIX" --with-sysroot --disable-nls --disable-werror
make
make install

This compiles the binutils (assembler, disassembler, and various other useful stuff), runnable on your system but handling code in the format specified by $TARGET.

—with-sysroot tells binutils to enable sysroot support in the cross-compiler by pointing it to a default empty directory. By default, the linker refuses to use sysroots for no good technical reason, while gcc is able to handle both cases at runtime. This will be useful later on.

GCC

Now, you can build GCC.

cd $HOMEsrc
 
# The $PREFIX/bin dir _must_ be in the PATH. We did that above.
which -- $TARGET-as || echo $TARGET-as is not in the PATH
 
mkdir build-gcc
cd build-gcc
..gcc-x.y.zconfigure --target=$TARGET --prefix="$PREFIX" --disable-nls --enable-languages=c,c++ --without-headers
make all-gcc
make all-target-libgcc
make install-gcc
make install-target-libgcc

We build libgcc, a low-level support library that the compiler expects available at compile time. Linking against libgcc provides integer, floating point, decimal, stack unwinding (useful for exception handling) and other support functions. Note how we are not simply running make && make install as that would build way too much, not all components of gcc are ready to target your unfinished operating system.

—disable-nls is the same as for binutils above.

—without-headers tells GCC not to rely on any C library (standard or runtime) being present for the target.

—enable-languages tells GCC not to compile all the other language frontends it supports, but only C (and optionally C++).

It will take a while to build your cross-compiler.

If you are building a cross compiler for x86-64, you may want to consider building Libgcc without the «red zone»: Libgcc_without_red_zone

Устанавливаем драйвера на st-link v2

Переходим на официальную страницу st-link v2

Внизу страницы скачиваем файл «STSW-LINK009» с описанием «ST-LINK, ST-LINK/V2, ST-LINK/V2-1 USB driver signed for Windows7, Windows8, Windows10».
При переходе на другую страницу нажимаем «Download» в нижней части страницы

Тут важно заметить, что если вы сидите в интернете не через VPN, то вам придется зарегистрироваться. Как это делать, я описывать не буду

После чего файл будет скачен.
Разархивировав архив выбираем файл установки драйвера согласно разрядности ОС. В моем случае, это «dpinst_amd64.exe».
Во время установки соглашаемся со всеми требованиями. И выбираем чекбокс «Всегда доверять программному обеспечению STMicroelectronics».

Troubleshooting

In general, verify that you read the instructions carefully and typed the commands precisely. Don’t skip instructions. You will have to set your PATH variable again if you use a new shell instance, if you don’t make it permanent by adding it to your shell profile. If a compilation seems to have gotten really messed up, type make distclean, and then start the make process over again. Ensure your un-archiever doesn’t change newline characters.

ld: cannot find -lgcc

You specified that you want to link the GCC low-level runtime library into your executable through the -lgcc‘ switch, but forgot to build and properly install the library.
If you got no warnings or errors while installing libgcc and you still have problems you can copy the library in your project and link it with -L. -lgcc
The libgcc is at $PREFIX/lib/gcc/$TARGET/<gcc-version>/libgcc.a .

Binutils 2.9

What’s alphabetically on the top or bottom is not necessarily the latest version. After 2.9 comes 2.10, 2.11, 2.12 and then there are more releases that are all newer and progressively more likely to build or support your choice of GCC version.

Building GCC: the directory that should contain system headers does not exist

You might encounter this error when building mingw32 targets, for example x86_64-w64-mingw32. The offending directory that can’t be found is $SYSROOT/mingw/include. If you look in your sysroot, you will, of course, realise that no such folder exists.

The solution is simply to create the empty folders:

mkdir -p $SYSROOTmingwinclude
mkdir -p $SYSROOTmingwlib

This will allow the build to proceed. The reason this happens is that the mingw32 (and mingw itself) configures INCLUDE_PATH and LIBRARY_PATH to be, as can be guessed, /mingw/include and /mingw/lib, instead of the defaults /usr/include and /usr/lib. Why the build fails even though nothing is required in those folders, and why it doesn’t just make them, is beyond me.

Sometimes GCC can’t build libsanitizer, if that happens append --disable-libsanitizer to the configure command.
This only applies for building a hosted compiler.

See Also

Articles

  • Cross-Compiler Successful Builds — combinations of GCC and Binutils which have been shown to work with this tutorial by OSDev.org members.
  • Target Triplet — on target triplets and their use
  • OS Specific Toolchain — going a step further and adding your own target.
  • LLVM Cross-Compiler — some compilers make things much easier.
  • Canadian Cross — making things yet more complicated.

Prebuilt Toolchains

These were built by people in the OSdev community for their own building needs and shared at will, without guaranteeing any support or that it will even work on your setup. YMMV.

Latests versions for Linux (many arch)

kernel.org various hosts/targets

For Linux i686 host

For Linux x86_64 host

i386-elf & i686-elf 7.1.0 target uploaded by TheAlmostGenius

The packages from phillid.tk below have been shrunk to about 10 MiB for each pair of packages (GCC & Binutils).
Please note that this has been achieved by enabling only the C front-end for GCC.
If you’re going to write your OS in any language but C or Assembly, these packages aren’t for you.
These are actually Pacman packages, but untarring them to / and rm-ing /.MTREE and other clutter dotfiles contained in the package will work the same.

For Windows host

For Windows Subsystem for Linux (Beta) host

i686-elf 6.1.0 target (extracts to a directory called «cross», don’t forget to install ‘make’ — I would recommend «apt-get install build-essential» to also add additional useful tools)

For macOS host

$ brew install x86_64-elf-gcc

ARM prebuilt toolchains for multiple host platforms

ARM provides it’s own prebuilt toolchain based upon GNU utilities for development targeting ARM systems.

GNU ARM Embedded Toolchain

Docker image

i686-elf 8.1.0 target

Компоненты MinGW

Проект MinGW поддерживает и распространяет несколько различных ключевых компонентов и дополнительных пакетов, включая различные порты GNU toolchain, такие как GCC и binutils, переведённые в эквивалентные пакеты. Эти утилиты могут использоваться из командной строки Windows или интегрированы в IDE. Пакеты могут быть установлены через командную строку в приложении mingw-get.

MinGW поддерживает динамические библиотеки, которые обычно называют по образцу и , и статические библиотеки, названные по типу , как и принято в UNIX и подобных ему системах.

Реализации заголовочных файлов Win32 и библиотек импорта Win32 имеют пермиссивную лицензию, а порты GNU доступны под GNU General Public License. Бинарные сборки полного пакета MSYS и отдельных MinGW GNU утилит доступны для скачивания на сайте MinGW.

MSYS

В дополнение, компонент MinGW, известный как MSYS (Minimal SYStem) предоставляет win32-порты окружения легковесной Unix-подобной оболочки, включающей rxvt и набор инструментов POSIX, достаточный для запуска скриптов autoconf. Однако, он не предоставляет компилятор языка C или файловую систему, чувствительную к регистру.

MSYS — это коллекция утилит GNU таких как , , и , которая позволяет собирать приложения и программы, зависящие от традиционных инструментов UNIX. Она предназначена для обновления MinGW и исправления недоработок командной строки. Примером будет разработка библиотеки, использующей пакет autotools для создания систем. Пользователи для этого скорее всего запустят нежели . Настройки консольных приложений требуют консольный интерпретатор, который не предоставляется Windows, но предоставляется MSYS.

Ошибочно считать, что MSYS — это «UNIX на Windows». MSYS сам по себе не содержит никаких компиляторов или библиотек C, следовательно он не предоставляет возможности портировать программы с UNIX на Windows и какого-либо специфического для UNIX функционала (например имена файлов, чувствительные к регистру). Пользователям, ищущим подобное, рекомендуется ознакомиться с Cygwin или Microsoft Interix.

mingwPORTs — пользовательские дополнения, разработанные для коллекции программного обеспечения MinGW. Они распространяются не в виде скомпилированных двоичных пакетов, а в форме интерактивных Bourne shell-скриптов, которые автоматически загружают и модифицируют исходный код, после чего компилируют и устанавливают его. Пользователи, желающие установить какое либо приложение из mingwPORT, должны перед этим установить MinGW и MSYS.

MinGW Installation Notes

MinGW may have problems with paths containing spaces, and if not, usually other programs used with MinGW will experience problems with such paths. Thus, we strongly recommend that you do not install MinGW in any location with spaces in the path name reference. You should avoid installing into any directory or subdirectory having names like «Program Files» or «My Documents«, etc.

No version numbering convention exists for MinGW as a whole. Each package has its own version number, and the installer version number does not correlate, in any way, with the version number of any individual package which it installs.

The preferred installation target directory is C:\MinGW

The preferred installation method is using the automated installer tool, as described below. While a manual installation is possible, we do not recommend it, unless you have a very old version of MS-Windows which is unable to run the graphical tool. Instructions for manual installation are provided below, if you really want (or need) to resort to it.

After installation you will need to perform some additional tasks yourself to ensure your MinGW applications will run. Most importantly, you will need to make changes to your PATH environment variable. Be careful: there are two PATH variables which can be changed, and changing the wrong one can have significant consequences. Instructions for changing the correct PATH variable are provided below.

You will also need to ensure you specify the correct installation target directory to the MinGW environment. While it is possible to install MinGW to a location other than C:\MinGW (e.g. on a different drive), you must ensure that the MinGW environment knows where it is located. Instructions for doing this are also provided below.

Debug helloworld.cpp

Next, you’ll create a file to configure VS Code to launch the GDB debugger when you press F5 to debug the program. From the main menu, choose Run > Add Configuration… and then choose C++ (GDB/LLDB).

You’ll then see a dropdown for various predefined debugging configurations. Choose g++ build and debug active file.

VS Code creates a file, opens it in the editor, and builds and runs ‘helloworld’.

The setting specifies the program you want to debug. Here it is set to the active file folder and active filename without an extension , which if is the active file will be .

By default, the C++ extension won’t add any breakpoints to your source code and the value is set to . Change the value to to cause the debugger to stop on the method when you start debugging.

The remaining steps are provided as an optional exercise to help you get familiar with the editing and debugging experience.

Start a debugging session

  1. Go back to so that it is the active file.
  2. Press F5 or from the main menu choose Run > Start Debugging. Before you start stepping through the code, let’s take a moment to notice several changes in the user interface:
  • The Integrated Terminal appears at the bottom of the source code editor. In the Debug Output tab, you see output that indicates the debugger is up and running.

  • The editor highlights the first statement in the method. This is a breakpoint that the C++ extension automatically sets for you:

  • The Run view on the left shows debugging information. You’ll see an example later in the tutorial.

  • At the top of the code editor, a debugging control panel appears. You can move this around the screen by grabbing the dots on the left side.

C/C++ configurations

If you want more control over the C/C++ extension, you can create a file, which will allow you to change settings such as the path to the compiler, include paths, C++ standard (default is C++17), and more.

You can view the C/C++ configuration UI by running the command C/C++: Edit Configurations (UI) from the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)).

This opens the C/C++ Configurations page. When you make changes here, VS Code writes them to a file called in the folder.

Here, we’ve changed the Configuration name to GCC, set the Compiler path dropdown to the g++ compiler, and the IntelliSense mode to match the compiler (gcc-x64)

Visual Studio Code places these settings in . If you open that file directly, it should look something like this:

You only need to add to the Include path array setting if your program includes header files that are not in your workspace or in the standard library path.

Compiler path

The extension uses the setting to infer the path to the C++ standard library header files. When the extension knows where to find those files, it can provide features like smart completions and Go to Definition navigation.

The C/C++ extension attempts to populate with the default compiler location based on what it finds on your system. The extension looks in several common compiler locations.

The search order is:

  • First check for the Microsoft Visual C++ compiler
  • Then look for g++ on Windows Subsystem for Linux (WSL)
  • Then g++ for Mingw-w64.

If you have Visual Studio or WSL installed, you may need to change to match the preferred compiler for your project. For example, if you installed Mingw-w64 version 8.1.0 using the i686 architecture, Win32 threading, and sjlj exception handling install options, the path would look like this: .

Building from source

The toolchain can be reproducibly built into a Docker image, or be
built and installed in the host environment.

To build and install all components, just do:

To reduce the size of the installation, removing some files that
aren’t necessary after building, run:

To build a Docker image with the toolchain, run:

Individual components of the toolchain can be (re)built by running
the standalone shellscripts listed within . However, if
the source already is checked out, no effort is made to check out a
different version (if the build scripts have been updated to prefer
a different version) — and likewise, if configure flags in the build-*.sh
scripts have changed, you might need to wipe the build directory under
each project for the new configure options to be taken into use.

Компилятор GCC. Первая программа на Windows

Последнее обновление: 18.05.2017

Для создания программ на Си необходим текстовый редактор, с помощью которого можно набрать исходный код. И также необходим компилятор,
который принимает файл с исходным кодом на Си и компилирует его в исполняемый файл.

При запуске установщика откроется следующее окно:

Нажмем на кнопку Next > и перейдем к следующему шагу:

Если версия ОС 64-битная, то в поле следует выбрать пункт x86_64. Остальные настройки
оставим по умолчанию и нажмем на кнопку Next >. На следующем шаге укажем путь, по которому будет устанавливаться пакет:

Можно оставить настройки по умолчанию. И после перехода к следующему шагу собственно начнется установка.

После завершения установки на жестком диске по пути, которое было выбрано для установки, появятся все необходимые файлы компиляторов.
В моем случае они находятся по пути C:\Program Files (x86)\mingw-w64\i686-7.1.0-posix-dwarf-rt_v5-rev0\mingw32\bin:

В зависимости от версии пакета точный путь может отличаться, но в любом случае все файлы будут располагаться по тому пути, который был указан на шаге установки.

В частности, файл gcc.exe как раз и будет представлять компилятор для языка Си.

Далее для упрощения запуска компилятора мы можем добавить путь к нему в Переменные среды. Для этого перейдем к окну
Система -> Дополнительные параметры системы -> Переменные среды:

И добавим путь к компилятору:

Итак, компилятор установлен, и теперь мы можем написать первую программу. Для этого потребуется любой текстовый редактор для набора исходного кода.
Можно взять распространенный редактор Notepad++ или даже обычный встроенный Блокнот.

Итак, создадим на жестком диске папку для исходных файлов. А в этой папке создадим новый файл, который назовем hello.c.

В моем случае файл hello.c находится в папке C:\c.

Теперь определим в файле hello.c простейший код, который будет выводить строку на консоль:

#include <stdio.h>		// подключаем заголовочный файл stdio.h
int main(void)					// определяем функцию main
{								// начало функции
	printf("Hello World! \n");	// выводим строку на консоль
	return 0;					// выходим из функции
}								// конец функции

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

#include <stdio.h>

Директива include подключает заголовочный файл stdio.h, который содержит определение функции printf, которая нужна для вывода строки на консоль.

Далее идет определение функции int main(void). Функция main должна присутствовать в любой программе на Си, с нее собственно и начинается
выполнение приложения.

Ключевое слово int в определении функции говорит о том, что функция возвращает целое число.
А слово void в скобках указывает, что функция не принимает параметров.

Тело функции main заключено в фигурные скобки {}. В теле функции происходит вывод строки на консоль с помощью функции printf, в которую передается выводимая строка «Hello world!».

В конце осуществляем выход из функции с помощью оператора return. Так как функция должна возвращать целое число, то после return указывается число 0.
Ноль используется в качестве индикатора успешного завершения программы.

После каждого действия в функции ставятся точка с запятой.

Теперь скомпилируем этот файл. Для этого откроем командную строку Windows и вначале с помощью команды cd перейдем к папке с исходным файлом:

cd C:\c

Чтобы скомпилировать исходный код, необходимо компилятору gcc передать в качестве параметра файл hello.c:

gcc hello.c

После этого будет скомпилирован исполняемый файл, который в Windows по умолчанию называется a.exe. И мы можем обратиться к этому файлу, и в этом случае консоль выведет
строку «Hello World!», собственно как и прописано в коде.

НазадВперед

Add a source code file

In the File Explorer title bar, select the New File button and name the file .

Install the C/C++ extension

Once you create the file and VS Code detects it is a C++ language file, you may be prompted to install the Microsoft C/C++ extension if you don’t already have it installed.

Choose Install and then Reload Required when the button is displayed in the Extensions view to complete installing the C/C++ extension.

If you already have C/C++ language extensions installed locally in VS Code, you’ll need to go to the Extensions view (⇧⌘X (Windows, Linux Ctrl+Shift+X)) and install those extensions into WSL. Locally installed extensions can be installed into WSL by selecting the Install in WSL button and then Reload Required.

Add hello world source code

Now paste in this source code:

Now press ⌘S (Windows, Linux Ctrl+S) to save the file. Notice how the file you just added appears in the File Explorer view (⇧⌘E (Windows, Linux Ctrl+Shift+E)) in the side bar of VS Code:

You can also enable to automatically save your file changes, by checking Auto Save in the main File menu.

The Activity Bar on the far left lets you open different views such as Search, Source Control, and Run. You’ll look at the Run view later in this tutorial. You can find out more about the other views in the VS Code User Interface documentation.

Technical Specifications

GCC also implements experimental support for some language Technical
Specifications published by the C++ committee.

Important: Because these Technical Specifications are
still evolving toward future inclusion in a C++ standard, GCC’s support
is experimental. No attempt will be made to maintain
backward compatibility with implementations of features that do not reflect
the final standard.

Technical Specification Document Available in GCC? Compiler Option SD-6 Feature Test
Concepts N4377 -fconcepts __cpp_concepts >= 201507
Transactional Memory N4514 (no atomic_cancel) -fgnu-tm __cpp_transactional_memory >= 201505
Coroutines N4649 In progress
Modules N4720 In progress

Test the New Compiler

All right, let’s compile some code that uses generic lambdas! Generic lambdas are part of the C++14 standard. They let you pass arguments to lambda functions as (or any templated type), like the one highlighted below. Create a file named with the following contents:

#include <iostream>

int main()
{
    auto lambda = [](auto x){ return x; };
    std::cout << lambda("Hello generic lambda!\n");
    return 0;
}

You can add files to your home directory in Cygwin using any Windows-based text editor; just save them to the folder (or similar) in Windows.

First, let’s see what happens when we try to compile it using the system GCC compiler provided by Cygwin:

If the system compiler version is less than 4.9, compilation will fail:

Now, let’s try it again using our freshly built GCC compiler. The new compiler is already configured to locate its include files in and its static libraries in . All we need to do is run it:

It works!

Contents of MinGW Packages

binutils: A native port of the GNU binutils. Amongst other tools, this package contains the assembler and linker, which will transform the output of the compiler into a binary executable. You must install this package, together with gcc-core, to obtain a correctly functioning compiler suite.
mingw-runtime: Header files and import libraries for the default C runtime library, (also known as msvcrt), which is required by MinGW compiled programs running on the Microsoft Windows operating system. You must install this package, together with gcc-core, to obtain a correctly functioning compiler suite.
w32api: Header files and import libraries for the Microsoft Windows operating system; this provides the Application Programming Interface (API) required to access the essential operating system service functions, which are required by any working native Windows application. You must install this package, together with gcc-core, to obtain a correctly functioning compiler suite.
gcc: A native port of the GNU gcc compiler. This is the application which parses source files, translating them to linkable object code. Note that the gcc package set is subdivided into a gcc-core package, which provides only a C compiler, with additional supplementary packages for additional programming languages. You must get at least the gcc-core package; if you also wish to add any supplementary languages, please ensure that you get the appropriate packages, with the same version number as the gcc-core package.
mingw-gdb: A native port of GNU debugger.
mingw32-make: A native port of GNU make. This application parses makefiles to create a project by following the rules expressed in the makefile.
mingw-utils: Miscellaneous utilities.

Run VS Code in WSL

Navigate to your helloworld project folder and launch VS Code from the WSL terminal with :

You’ll see a message about «Installing VS Code Server». VS Code is downloading and installing a small server on the Linux side that the desktop VS Code will then talk to. VS Code will then start and open the folder. The File Explorer shows that VS Code is now running in the context of WSL with the title bar .

You can also tell the remote context from the Status bar.

If you click on the Remote Status bar item, you will see a dropdown of Remote commands appropriate for the session. For example, if you want to end your session running in WSL, you can select the Close Remote Connection command from the dropdown. Running from your WSL command prompt will restart VS Code running in WSL.

The code . command opened VS Code in the current working folder, which becomes your «workspace». As you go through the tutorial, you will see three files created in a folder in the workspace:

  • (compiler path and IntelliSense settings)
  • (build instructions)
  • (debugger settings)

Other significant improvements

  • To allow inline expansion of both
    and , the existing instruction
    patterns used for non-overlapping memory copies have been renamed to
    . The name is now used
    for overlapping memory moves, consistent with the
    library functions and .
  • For many releases, when GCC emits a warning it prints the option
    controlling that warning. As of GCC 10, that option text is now a
    clickable hyperlink for the documentation of that option (assuming a
    sufficiently capable terminal).
    This behavior can be controlled via a new

    option (along with various environment variables and heuristics
    documented with that option).

Компиляция и запуск программ C, C++

Сначала посмотрим, как скомпилировать и запустить простую программу, написанную на языке Си.

Компиляция и запуск программ на C

Напишите свой код/программу в любимом редакторе CLI/GUI.

Я собираюсь написать свою программу на Си с помощью редактора nano.

Примечание. Вам необходимо использовать расширение .c для программ на Си или .cpp для программ на Си++.

Скопируйте/вставьте следующий код:

Нажмите Ctrl+O и Ctrl+X для сохранения и выхода из файла.

Чтобы скомпилировать программу, запустите:

Или:

Если в вашем коде/программе есть синтаксические или семантические ошибки, они будут отображены. Сначала необходимо их исправить, чтобы двигаться дальше. Если ошибки нет, то компилятор успешно сгенерирует исполняемый файл ostechnix в текущем рабочем каталоге.

Наконец, запустите программу с помощью команды:

Вы увидите вывод, как показано ниже:

Чтобы скомпилировать несколько исходных файлов (например, source1 и source2) в исполняемый файл, запустите:

Для разрешения предупреждений, необходима отладка символов на выходе:

Скомпилировать исходный код в инструкции ассемблера:

Скомпилировать исходный код без связывания:

Вышеприведенная команда создаст исполняемый файл под названием source.o.

Если ваша программа содержит математические функции:

За более подробной информацией обращайтесь к man-страницам (страницы руководства).

Компиляция и запуск программ на C++

Напишите вашу C++ программу в любом редакторе по вашему выбору и сохраните ее с расширением .cpp.

Пример простой C++ программы:

Программа:

Чтобы скомпилировать эту программу на C++ в Linux, просто запустите:

Если ошибок не было, то можно запустить эту Си++ программу под Linux с помощью команды:

Выведет:

В качестве альтернативы мы можем скомпилировать приведенную выше программу на C++, используя команду «make», как показано ниже.

Вы заметили? Я не использовал расширение .cpp в вышеприведенной команде для компиляции программы. Нет необходимости использовать расширение для компиляции Си++ программ с помощью команды make.

Запустите, используя команду:

За более подробной информацией обращайтесь к man-страницам.

Надеюсь, что статья помогла.

Background

Exception handling: SJLJ, DWARF, and SEH

Some packages like MinGW-builds and TDM-GCC let you choose which exception implementation you want to use. You must ensure you use the same compiler used to build the Qt you use in order to avoid linker errors. If you choose to change the exception handling mechanism, you will need to rebuild all code, mostly because the libgcc shared library name is different between the exception handling settings.

SJLJ (setjmp/longjmp):

  • available for 32 bit and 64 bit
  • allows exceptions to traverse through e.g. windows callbacks

DWARF (DW2, dwarf-2)

  • available for 32 bit only
  • no permanent runtime overhead
  • needs whole call stack to be dwarf-enabled, which means exceptions cannot be thrown over e.g. Windows system DLLs.

SEH (zero overhead exception)

  • will be available for 64-bit GCC 4.8.

From TDM-GCC readme:

«GCC currently supports two methods of stack frame unwinding: Dwarf-2 (DW2) or
SJLJ (setjmp/longjmp). Until recently, only SJLJ has been available for the
Windows platform. This affects you, the end user, primarily in programs that
throw and catch exceptions. Programs which utilize the DW2 unwind method
generally execute more quickly than programs which utilize the SJLJ method,
because the DW2 method incurs no runtime overhead until an exception is thrown.
However, the DW2 method does incur a size penalty on code that must handle
exceptions, and more importantly the DW2 method cannot yet unwind (pass
exceptions) through «foreign» stack frames: stack frames compiled by another
non-DW2-enabled compiler, such as OS DLLs in a Windows callback.

This means that you should in general choose the SJLJ version of the TDM-GCC
builds unless you know you need faster exception-aware programs and can be
certain you will never throw an exception through a foreign stack area.

As distributed, the SJLJ and DW2 packages of TDM-GCC can coexist peacefully
extracted to the same directory (i.e. any files in common are for all intents
and purposes identical), because the driver executables (the ones in the «bin»
directory) are suffixed with «-dw2» for the DW2 build, and the libraries and
other executables hide in another «-dw2» directory in «lib(exec)/gcc/mingw32».
This allows you to use the same single addition to your PATH, and use DW2
exceptions only when you need them by calling «gcc-dw2», etc. If you truly want
DW2 exceptions as the default when calling «gcc» (from Makefiles or configury
systems, for example), you can rename or copy the suffixed executables to their
original names.»

DW2 Issues

  • Calling FreeLibrary to unload a dll that links to both dynamic libgcc_s_dw2 and a library that links to static libgcc_s_dw2 results in a crash

GCC Threading model (posix vs win32)

Mingw-Builds (and the experimental rubenvb packages) also let you choose between the threading model internally used by (lib)gcc:

  • posix (built upon MinGW-w64’s winpthreads)
    • «an implementation of POSIX threads for win32 is also available under the experimental directory. Its main goal is to support C+
    • enables C11 library features contained in the headers <thread>, <mutex>, and <future>.
    • Performance degradation in specific scenarios. C11 functionality is significantly slower than native Win32 implementation or even MSVS2012’s implementation.
  • win32
    • uses native Win32 threading functions.
    • no C11 <thread>, <mutex>, or <future>
    • best performance
Оцените статью
Рейтинг автора
5
Материал подготовил
Андрей Измаилов
Наш эксперт
Написано статей
116
Добавить комментарий