Как установить codeblocks с компилятором c
Перейти к содержимому

Как установить codeblocks с компилятором c

  • автор:

Installing a supported compiler

When you launch Code::Blocks for the first time, it will scan the system for any supported compilers. Once this scan has finished, Code::Blocks will have been correctly configured for any detected compilers. Code::Blocks will also have default configurations even for compilers that were not found.

This article is a guide for obtaining, installing, and configuring the various compilers that Code::Blocks can use.

Contents

Compiler-neutral setup steps

Before using a compiler with Code::Blocks you have to install it. The method for installing the compiler depends on the Operating system you’re using, the Compiler you intend to use and so on. If you installed the compiler on its default installation directory, there is nothing more to configure (if the compiler is natively supported by Code::Blocks). Launch Code::Blocks and you’re all set :)

  • If that is not the case, launch Code::Blocks. If it is the first time you launch it, the compiler auto-detection will be launched.
  • If your compiler was not auto-detected, go to «Settings->Compiler and Debugger->Global Compiler settings->Toolchain executables», select the compiler you installed and press «Auto-detect».
  • If you get a message saying that the compiler was auto-detected, congratulations!
  • If not, then press the button with the three dots next to the «Auto-detect» button and select the installation directory of your compiler manually.

NOTE: The compiler’s installation directory is exactly this: the installation directory. Not the «bin» subdirectory nor any other.

Windows

Once you’ve installed a new compiler, be sure to read the Compiler-neutral setup steps at the end of this article.

At the time of this writing, Code::Blocks supports the following compilers in Windows:

These compilers are generally still under active development by their publishers, so a new version of their software could be released that is incompatible with the current version of Code::Blocks.

The following compilers are still supported by Code::Blocks, but are no longer available from their original publishers.

  • Microsoft’s Visual C++ 2003 — 2010
  • Borland’s C/C++ Free Compiler 5.5

The following publishers have released newer versions of their compilers which should be tested against the current configuration. In other words, it is not known yet whether these compilers still work with Code::Blocks.

MinGW/GCC

The official MinGW website is at mingw.org. A MinGW-bundled version of the latest Code::Blocks release is available from the Code::Blocks download page. If you install this version, the GCC compiler will be automatically detected and set as the default. Also you can use the TDM’s GCC/mingw32 Builds from [1] or [2].

Note: In any case, if you don’t install MinGW in C:\MinGW, you’ll need to update the configuration of GCC in Code::Blocks.

Official MinGW.org

You can install MinGW yourself, by using an automatic downloader/installer or by downloading and unpacking the required packages by hand from mingw.org, here: [3].

Packages required (suggested) for MinGW/GCC v3.4.5:

  • Compiler:
    • gcc-build-3.4.5-20060117-3.tar.gz
    • gcc-core-3.4.5-20060117-3.tar.gz
    • gcc-g++-3.4.5-20060117-3.tar.gz
    • binutils-2.19.1-mingw32-bin.tar.gz
    • gdb-6.8-mingw-3.tar.bz2
    • mingw32-make-3.81-20080326.tar.gz
    • mingwrt-3.16-mingw32-dev.tar.gz
    • mingwrt-3.16-mingw32-dll.tar.gz
    • w32api-3.13-mingw32-dev.tar.gz

    Packages required (suggested) for MinGW/GCC v4.4.0:

    • Compiler:
      • gcc-full-4.4.0-mingw32-bin-2.tar.lzma
      • binutils-2.19.1-mingw32-bin.tar.gz
      • gdb-6.8-mingw-3.tar.bz2
      • mingw32-make-3.81-20080326.tar.gz
      • mingwrt-3.16-mingw32-dev.tar.gz
      • mingwrt-3.16-mingw32-dll.tar.gz
      • w32api-3.13-mingw32-dev.tar.gz
      HOWTO: Use Cygwin 1.7 with Code::Blocks

      Cygwin 1.7 changed the way symlinks were created and handled when invoked from a command prompt. I couldn’t find a way to force CB to use a unix-link shell, but was able to find a work around when perusing the Cygwin mailing lists.

      The symptom would show up with a message similar to the one below:

      Executing the same command from the CMD.EXE prompt yields an «Access is denied» message. This was how I was able to track down why the issue occurred. For more info, see this cygwin mailing list thread: http://www.mail-archive.com/cygwin@cygwin.com/msg104088.html

      The solution is to point your compiler and linker directly to the version of gcc and g++ that you want to use.

      In my case, I wanted to use gcc-4.exe and g++-4.exe and so, I went into Settings->Compiler and Debugger->Toolchain executables. There I changed the «C Complier», «C++ Compiler» and «Linker for dynamic libs» to point to gcc-4.exe, g++-4.exe and g++-4.exe.

      After this, compilation and linking worked fine.

      It would also be a good idea to add an environment variable CYGWIN with a value of nodosfilewarning in Settings->Environment->Environment Variables. This eliminates the following (harmless) warning message:

      (Unofficial) TDM — «Twilight Dragon Media»

      These packages are called TDM’s GCC/mingw32 Builds and can be obtained from [/index.php/topic,10508.0.html] or [4].

      Packages required (suggested) for TDM’s GCC/mingw32 Builds v4.4.1-tdm-2 SJLJ: . which can be found here: [5] under: TDM-GCC 4.4 series -> 4.4.1-tdm-2 SJLJ.

      • Compiler:
        • gcc-4.4.1-tdm-2-core.zip
        • gcc-4.4.1-tdm-2-g++.zip
        • binutils-2.19.1-mingw32-bin.tar.gz
        • gdb-6.8-mingw-3.tar.bz2
        • mingw32-make-3.81-20080326-3.tar.gz
        • mingwrt-3.16-mingw32-dev.tar.gz
        • mingwrt-3.16-mingw32-dll.tar.gz
        • w32api-3.13-mingw32-dev.tar.gz

        These packages are included in both the Bundled Installer and the On-Demand Installer available via TDMs page referenced above for users who do not wish to download and install them manually.

        Embarcadero C++ Compiler BCC32C

        Formerly Borland’s C++ Compiler, this compiler is now published by Embarcadero, with active on-going development; the current version is 10.1 as of this writing. Go to their product download page to download. You will be asked to enter some registration information (registration is free) then the download will begin. You will receive a ZIP archive which contains installation instructions in a text file in the root directory of the archive; it does not have an installer program.

        Digital Mars C/C++ Free Compiler

        Go to DigitalMars. Accept the license agreement and you’ll be redirected to a page containing download links.

        In that page, download:

        • The Digital Mars C/C++ Compiler (dm8**c.zip)
        • The Basic Utilities (bup.zip)
        • The STLport library (stlport.zip)

        Open dm\bin\sc.ini in a text editor, and replace the line

        Intel C++ Compiler

        Please note that on Windows platform, Intel C/C++ compiler requires Microsoft Visual C++[6] to be present in your system in order to function properly. It will not compile any C++ program without it. You should also note that Windows SDK[7] shall be installed in order to compile Windows app.

        Code::Blocks (C::B) is now able to detect (from svn revision 4967 onwards) Intel C/C++ compiler and it’ll then automatically setup the MSVC compiler so that the Intel compiler works as intended. However if you wish to manually install the Intel C/C++ compiler, then follow the following steps.

        • Go to Settings > Compilers and debuggers and then select Intel C/C++ compiler.
        • Click on the Toolchain executables tab. Point to the installation directory, e.g. C:\Program Files\Intel\Compiler\C++\10.1.020\IA32 , inside the Compiler’s installation directory textbox.
        • Click on the Additional Paths tab and fill in the directories pointing to MSVC bin directory and the Windows SDK directory. It may look like-
        • Click on the Search directories tab and add the include directories containing headers offered by Intel C/C++ compiler, MSVC compiler and the Windows SDK headers to Compiler and Resource compiler. It may look like-
        • Click on the Linker tab under Search directories tab and add the directories containing libraries offered by Intel C/C++ compiler, MSVC compiler and the Windows SDK. It may look like-

        Click on the OK button to save the settings. Now you should be able to use Intel C/C++ compilers on Windows with C::B.

        Note: The directories specified above may be different on your PC.

        Digital Mars D Compiler for Windows

        Now Digital Mars D Compiler (DMD) supports 32bit Windows, and in future it will support 64bit Windows. If you want to build D program in CodeBlocks on 32bit Windows, please following the instructions as bellow.

        1). Install DMD(2.0) into your Windows system.

        You should correctly combine the DMD compiler and install it into your system. Please view the instructions on digitalmars.com website. DMD for Windows http://www.digitalmars.com/d/2.0/dmd-windows.html

        2). Settings in CodeBlocks.

        You should add correct DMD pathes into CodeBlocks Global compiler settings

        The «D:\Program\DMD2» or «D:\Program\DMC\bin» here should change to your own DMD or DMC path in your system.

        3). Testing D program in CodeBlocks.

        In CodeBlocks, produce a D Application project, and input your own D code into the .d file in the project, then build/run.

        Linux

        At the time of this writing, Code::Blocks supports the following compilers in Linux:

        Digital Mars D Compiler for Linux

        Now Digital Mars D Compiler (DMD) supports 32bit and 64bit Linux, and ‘support Linux library’ is under construction. If you want to build D program in CodeBlocks on 32bit and 64bit Linux, please following the instructions as bellow.

        1). Install DMD(2.0) into your Linux system.

        You should correctly combine the DMD compiler and install it into your system. Please view the instructions on digitalmars.com website. DMD for Linux http://www.digitalmars.com/d/2.0/dmd-linux.html

        2). Settings in CodeBlocks.

        A). 32bit Linux & 32bit DMD2.

        On 32bit Linux, you should combine 32bit DMD2 from DMD2 source and install it into your system.

        You should add correct DMD pathes into CodeBlocks Global compiler settings.

        If you installed DMD2 to a different path, please modify «/opt/dmd2» to your own DMD2 path.

        B1). 64bit Linux & 64bit DMD2.

        On 64bit Linux, you can combine 64bit DMD2 from DMD2 source and install it into your system.

        You should add correct DMD paths into CodeBlocks Global compiler settings.

        If you installed DMD2 to a different path, please modify «/opt/dmd2» to your own DMD2 path.

        B2). 64bit Linux with 32bit DMD2.

        On 64bit Linux, you can combine 32bit DMD2 with 64bit together from DMD2 source and install them into your system.

        You should add correct DMD paths into CodeBlocks Global compiler settings.

        If you installed DMD2 to a different path, please modify «/opt/dmd2» to your own DMD2 path.

        3). Testing D program in CodeBlocks.

        In CodeBlocks, produce a D Application project, and input your own D code into the .d file in the project, then build/run.

        Downloading the GNU GCC compiler & GDB debugger

        Under Linux you’ll, most probably, already have everything that is needed in order to compile. All major Linux distributions (RedHat, Debian, SuSE, Mandriva, Gentoo, ArchLinux, etc) come with GCC & GDB preinstalled. To make sure you have have gcc installed, go to your terminal and type ‘gcc -v’. In case you have GCC installed, you will get GCC’s compile options and version number.

        Mac OS X

        The Mac OS X port efforts has began recently, but it should be a matter of time until these compilers will be supported:

        Downloading the GNU GCC compiler & GDB debugger

        Under Mac you’ll need to install a compatible version Xcode Tools from http://developer.apple.com/tools/ (or http://developer.apple.com/downloads). You need the «Command Line Tools».

        This will install Apple versions of:

        Setting up compiler switches

        Usually you need to tweak the compiler options to be able to compile C++ applications — that’s the stuff Xcode hides from your eyes, but you better should know. You need to point to the GNU compiler’s C/C++ include folders, to the GNU linkers libraries folder and a adjust the compiler options to setup the GNU compiler root path. Those path’s differ depending on what hardware (processor architecture) and what version of MacOS is used. For an Intel based Mac with MacOS 10.6.2 and Xcode v3.2.2 the following should work:

        Compiler search directories («include» folders):

        Linker search directories («library» folders):

        Additional compiler flags:

        -isysroot /Developer/SDKs/MacOSX10.6.sdk -mmacosx-version-min=10.6 -gdwarf-2

        Remote Compilation

        Remote compilation is not directly supported by Code::Blocks, however, the following articles explain two remote compilation systems, which use 3rd party programs to provide this functionality:

        Misc. Custom Compilers

        There are several user contributions for different (non-C/C++) compiler which are listed here:

        Начинаем работать с С++

        Начинаем работать с С++

        С++ на порядок более сложный язык, чем множество других, популярных сегодня языков программирования. У новичков первые сложности возникают уже при попытке установить необходимые средства для разработки. Причина — большое разнообразие компиляторов (собирают из исходных файлов исполняемый файл программы) и интегрированных средств разработки. Вот некоторые наиболее популярные интегрированные среды разработки:

        • Visual Studio Community (бесплатна для индивидуального использования)
        • Qt Creator (бесплатная, есть ограничения при лицензировании)
        • CLion (30-ти дневная полнофункциональная пробная версия)
        • Code Blocks (бесплатна)

        Указанные выше программы являются эдакими комбайнами, которые будут помогать Вам от начала создания первого файла и до развертывания готового проекта на конечных устройствах. Безусловно, возможности, которые они предоставляют трудно переоценить, однако, для начала, крайне желательно понять основы — как все это работает «под капотом». Поэтому хватить простого Notepad++ и компилятора. Компиляторов (наборы компиляторов) тоже существует множество, вот некоторые из них:

        • Clang
        • GCC
        • Cygwin
        • MinGW
        • Microsoft Visual C++ Build Tools

        Самый простой способ установить и редактор и компилятор С++ — это установить среду разработки Code Blocks со встроенным компилятором MinGW. После установки добавьте в переменную среды PATH путь (в моем случаем он такой — C:\Program Files\CodeBlocks\MinGW\bin) к папке с компилятором g++. Но имейте ввиду, что, если вы работате с Windows ниже версии 10, то скорее всего, Вам придется доустанавливать какие-либо дополнительные системные компоненты.

        После установки компилятора С++ (g++), выполните в консоли следующую команду:

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

        После того как все установлено, создайте файл main.cpp со следующим содержимым:

        // подключаем файл — для вывода в консоль
        #include <iostream>

        // с этого метода начинается работа программы
        int main() <
        // пишем приветствие в консоль. std — это название пространства имен, std::cout — объект для работы с консолью
        // оператор << перенаправляет вывод в консоль, std::endl — символ перевода строки
        std::cout << "Привет, С++ !" << std::endl;

        // код 0 — штатное завершение программы
        return 0;
        >

        Соберите файл с помощью следующей команды:

        C:/> g++ main.cpp -o hello.exe

        Запустите программу следующим образом:

        Таким образом, Вы установили компилятор и создали свою первую программ на С++.

        Установка CodeBlocks в Ubuntu 20.04

        Code::Blocks — свободная кроссплатформенная среда разработки. Написана на языке программирования C++ и использует библиотеку wxWidgets. Имеет открытую архитектуру, благодаря которой может масштабироваться за счёт подключаемых модулей. Поддерживает следующие языки программирования» С, C++, D (с ограничениями) и Fortran.

        Программа разрабатывается для Windows, Linux и Mac OS X. Можно собрать из исходников практически под любую Unix-подобную систему, например FreeBSD, PC-BSD. В данной статье будет рассмотрена установка CodeBlocks Ubuntu 20.04 при помощи пакетного менеджера apt и из официального сайта.

        Установка CodeBlocks в Ubuntu 20.04

        Для начала необходимо обновить индекс пакетов при помощи команды:

        sudo apt update

        IShyBYAAAAASUVORK5CYII=

        Далее необходимо установить пакет codeblocks при помощи команды:

        sudo apt -y install codeblocks

        f46bx4ImIanHAAAAAElFTkSuQmCC

        После установки программу можно найти, введя в поиске слово code в главном меню:

        194Unun9M0bowAAAABJRU5ErkJggg==

        Если при попытке установки при помощи пакетного менеджера apt команда выдаст ошибку: «Unable to locate package codeblocks» то перед установкой программы необходимо включить репозиторий universe. Для этого выполните в терминале команду:

        sudo add-apt-repository universe

        Обновлять индексы пакетов не надо так как программа обновит их автоматически. После этого программу можно попробовать установить снова.

        Как пользоваться CodeBlocks

        Запуск CodeBlocks

        При первом запуске программа предложит выбрать компилятор:

        AeqdXXxXhfHqAAAAAElFTkSuQmCC

        Компилятор уже должен заранее присутствовать в системе. Если при первом запуске программы в списке нету ни одного компилятора на выбор, необходимо его установить. Можно воспользоваться компилятором GCC (считается стандартом для Ubuntu). Его установка описана в статье Установка GCC в Ubuntu 20.04

        Главное окно программы выглядит следующим образом:

        j8BaELFzwMWqgAAAABJRU5ErkJggg==

        Создание нового проекта

        Для создания нового проекта необходимо выбрать пункт Create a new project в главном меню:

        YAAAAASUVORK5CYII=

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

        JtqFRpbJ3RgAAAABJRU5ErkJggg==

        На следующем шаге необходимо выбрать язык программирования, на котором будет разработаться приложение:

        XlDT8cANVLvTRio4ghc3rIEK6PMVvaguCQOY9pVAQgbhNs9OvBuoByhuuf+xbB637Gft1r9C16uB+uHI4z9AAAAAElFTkSuQmCC

        Далее необходимо задать имя для проекта и путь до директории, где будет храниться проект:

        8HlCLGG7fuZeAAAAAASUVORK5CYII=

        На последнем шаге можно выбрать компилятор, а также задать опции для отладки. Данный шаг можно пропустить и нажать на кнопку Finish:

        GcnkgpZVlsEAAAAASUVORK5CYII=

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

        WzepuKRY5JAAAAAElFTkSuQmCC

        Выводы

        В этой статье мы рассмотрели, как установить CodeBlocks Ubuntu 20.04, а также как запустить и начать свой первый проект в этой программе. Сам процесс установки несложен. Так же можно выбрать каким способ произвести установку программы.

        Setting up Code::Blocks on Windows

        This tutorial gives you easy-to-follow instructions, with screenshots, for setting up a compiler (the MINGW compiler), a tool that will let you turn the code that you write into programs, and Code::Blocks, a free development environment for C and C++. This tutorial explains how to install Code::Blocks on Windows 2000, XP, Vista or Windows 7. Note: the easiest way to get a compiler is to use Cee Studio, from our sponsor. It will let you run your code in your browser, without installing anything. If you’re running Linux, go here to learn how to use GCC; if you’re on OS X, go here to get set up using Apple XCode.

        Step 1: Download Code::Blocks

        • Go to this website: http://www.codeblocks.org/downloads
        • Follow the link to «Download the binary release» (direct link)
        • Go to the Windows 2000 / XP / Vista / 7 section
        • Look for the file that includes mingw in the name. (The name as of this writing was codeblocks-10.05mingw-setup.exe; the 10.05 may be different).
        • Save the file to your desktop. It is roughly 74 megabytes.

        Step 2: Install Code::Blocks

        • Double click the installer.
        • Hit next several times. Other setup tutorials will assume you have installed in C:\Program Files\CodeBlocks (the default install location), but you may install elsewhere if you like
        • Do a Full Installation
        • Launch Code::Blocks

        Step 3: Running in Code::Blocks

        You will be prompted with a Compilers auto-detection window:

        Compiler Auto-Detection Window

        When you get the compiler auto-detection window, just hit OK. Code::Blocks may ask if you want to associate it as the default viewer for C/C++ files—I’d suggest you do. Click on the File menu, and under «New», select «Project. «

        The following window will come up:

        New Project Window

        Click on «Console Application» and hit the «Go» button.

        Click next until you get to the Language Selection Dialog:

        Language selection dialog

        You’ll be asked to choose whether you want to use C or C++. If you’re not sure, use C++. Otherwise, choose based on the language you are learning. (You can find tutorials here on both C and C++.)

        After clicking «Next», Code::Blocks will then prompt you with where you’d like to save the console application:

        Project Name and Location

        I’d recommend you put it in its own folder, as it may create several files (this is especially true if you create other types of projects). You will need to give your project a name, anything will be fine.

        Clicking «Next» again will prompt you to set up your compiler:

        Compiler Setup

        You don’t need to do anything here. Just accept the defaults by hitting «Finish».

        You can now open the main.cpp file on the left:

        Main Editor View

        (You may need to expand the contents of the «Sources» folder if you don’t see main.cpp.)

        At this point, you will have your main.cpp file, which you can modify if you like. For now, it just says «Hello World!», so we can run it as is. Hit F9, which will first compile it and then run it.

        Running Program

        You now have a running program! You can simply edit main.cpp and then hit F9 to compile it and run it again.

        Now that you’ve finished setting your compiler up, it’s time to learn to program: Intro to C++ (or if you’re learning C, Intro to C).

        Troubleshooting

        The most common error people see if things don’t work is a message like

        «CB01 — Debug» uses an invalid compiler. Probably the toolchain path within the compiler options is not setup correctly?! Skipping. «

        First, make sure that you downloaded the right version of Code::Blocks, the one that included MinGW. If that doesn’t solve the problem, it is likely a problem with compiler auto-detection. Here’s how you can check your current «auto-detected» state. Go to «Settings|Compiler and Debugger. «. Then on the left, choose «Global Compiler Settings» (it has a gear icon) and on the right, select the «Toolchain executables» tab. This tab has a «Auto-detect» button that you can use. That might fix the problem—if it doesn’t, you can manually fill out the form. Here’s a screenshot demonstrating what things look like on my system. Change the path marked «Compiler’s installation directory» if you installed to a different location, and make sure everything else is filled in as shown.

        Once you’ve done that, try pressing F9 again to see if you get a running program.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *