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

от admin

Установка Code::Blocks и MINGW, бесплатный компилятор C и C++, на Windows

В этом пособии вы найдете легкие инструкции со скриншотами для установки компилятора (MINGW компилятора), инструмента, который позволит вам преобразовать код, который вы пишете в программу и Code::Blocks, бесплатную среду разработки для C и C++. В этом пособии объясняется как установить Code::Blocks на Windows 2000, XP, Vista или Windows 7. Примечание: если вы работаете в Linux, перейдите по ссылке, чтобы узнать, как использовать GCC, если вы используете OS X, нажмите здесь, чтобы настроить его с помощью Apple XCode.

Шаг 1: Скачивание Code::Blocks
  • Зайдите на этот сайт
  • Перейдите по ссылке Download the binary release (прямая ссылка)
  • Перейдите в раздел Windows 2000 / XP / Vista / 7
  • Найдите файл, у которого в названии есть mingw . (Название на момент написания статьи было codeblocks-10.05 mingw-setup.exe; версии 10.05 могут быть разными).
  • Сохраните файл на рабочем столе. Это примерно 74 мегабайта.
Шаг 2: Установка Code::Blocks
  • Дважды щелкните на программу установки.
  • Нажмите next несколько раз. Другие пособия по установке предполагают, что вы устанавливаете в C:\Program Files\CodeBlocks (место установки по умолчанию), но вы при желании можете установить в любом другом месте
  • Проведите полную установку
  • Запустите Code::Blocks
Шаг 3: Запуск в Code::Blocks

Перед вами откроется окно Compilers auto-detection :

Когда перед вами появится окно автоматического обнаружения компилятора, просто нажмите OK. Code::Blocks может спросить, хотите ли вы связать его с просмотром C/C++ файлов по умолчанию — я советую вам это сделать.

New Project Window

Нажмите на меню File и в разделе New , выберите Project . Появится следующее окно:

New Project Window

Нажмите на Console Application , а затем Go . Нажимайте next , пока не дойдете до Language Selection Dialog :

Language selection dialog

Вам будет предложено выбрать между C или C++. Если вы не уверены, используйте C++. В противном случае, выберите язык, который вы изучаете. (Вы можете найти пособия по С и С++ здесь.)

После нажатия Next , Code::Blocks спросит, где вы хотите сохранить консольное приложение:

Project Name and Location

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

После нажатия Next еще раз, вам будет предложено настроить компилятор:

Compiler Setup

Вам не нужно ничего делать, просто нажмите Finish и используйте значения по умолчанию.

Теперь слева вы можете открыть файл main.cpp:

Main Editor View

(Вам, возможно, потребуется раскрыть содержание папки Sources , если вы не видите main.cpp).

Теперь у вас есть свой файл main.cpp , который вы можете изменять при желании. На данный момент, он просто говорит: Hello World! , поэтому мы можем запустить его таким, какой он есть. Нажмите F9 , для того чтобы сначала скомпилировать, а потом запустить его.

Running Program

Теперь у вас есть работающая программа! Вы можете просто отредактировать main.cpp, а затем нажать клавишу F9, чтобы скомпилировать и запустить его снова.

Теперь, когда вы закончили установку компилятора, самое время учиться программированию: на C++ (или, если вы изучаете C, программирование на C).

Поиск и устранение неисправностей

Если что-то не работает, то чаще всего появляется сообщение:

Во-первых, убедитесь, что вы скачали правильную версию Code::Blocks, ту, которая содержит MinGW . Если так вы не решите проблему, то, скорее всего, проблема с автоматическим обнаружением компилятора. Вы можете проверить текущее состояние «авто-определения» так. Перейдите в Settings|Compiler and Debugger. . Затем слева выберите Global Compiler Settings (он имеет значок с изображением шестеренки), а справа, выберите вкладку Toolchain executables . В этой вкладке есть Auto-Detect , который можно использовать. Это может решить проблему — если нет, вы можете сделать это вручную. На скриншоте показано, как все это выглядит на моей системе. Измените путь с пометкой Compiler’s installation directory , если вы установили в другом месте, и убедитесь, что все остальное заполняется как показано на рисунке.

После того как вы сделали это, попробуйте нажать F9 еще раз, чтобы проверить, можете ли вы запустить программу.

Инструкция по установке ПО

Это краткая версия, как установить такую же среду, как в лаборатории. Больше вариантов (например, для Mac или не CodeBlocks) — в общей инструкции.

В Windows XP каталоги установки и проектов не должны содержать пробелов и кириллицы.

Компилятор GCC 8.1 (MinGW-w64)

Создать каталог C:\MinGW и распаковать в него архив.

Официальный сайт GCC: https://gcc.gnu.org.
Официальный сайт MinGW-w64 (версия для Windows): https://mingw-w64.org.

Среда разработки CodeBlocks

    CodeBlocks, все по умолчанию, но в конце не запускать среду.
  1. Открыть «Проводник», в строку адреса ввести %AppData%\Roaming и нажать Enter (для редактирования адреса надо нажать на значок папки слева от адреса).
  2. Распаковать в открывшуюся папку архив настроек. (Если каталог CodeBlocks уже существует, заменить его.)

Система контроля версий Git

Сборочная система CMake

При установке выбрать вариант «Add CMake to the system PATH for all users».

Козлюк Д. А., Мохов А. С., Василькова П. Д. для кафедры Управления и информатики НИУ «МЭИ», 2019 г.

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:

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

        Goto http://www.codeblocks.org/downloads. Click «Download the binary release». Select your operating platform (e.g., Windows 2000/XP/Vista/7). Download the installer with GCC Compiler, e.g., codeblocks-13.12mingw-setup.exe (98 MB) (which includes MinGW’s GNU GCC compiler and GNU GDB debugger).

        Step 2: Install

        Run the downloaded installer. Accept the default options.

        Verify the Compiler’s and Debugger’s Path : (For CodeBlocks 13.12 For Windows) Goto «Settings» menu ⇒ «Compiler. » ⇒ In «Selected Compiler», choose «GNU GCC Compiler» ⇒ Select tab «Toolchain Executables» ⇒ Check the «Compiler’s Installation Directory». It shall be set to the «MinGW» sub-directory of the CodeBlocks installation directory, for example, suppose that CodeBlocks is installed in » c:\Program Files\codeblocks «, set it to » c:\Program Files\codeblocks\MinGW «.

        Similarly, check the debugger’s path. Goto «Settings» menu ⇒ «Debugger. » ⇒ Expand «GDB/CDB debugger» ⇒ Select «Default» ⇒ In «Executable path», provide the full-path name of » gdb.exe «, for example, » c:\Program Files\codeblocks\MinGW\bin\gdb.exe «.

        Notes For CodeBlocks 13.12 For Windows (Jan 2014)

        I encountered problem running debugger with CodeBlocks 13.12 bundled with MinGW (gcc v4.7.1 and gdb 7.5).

        I resolved by installing the latast MinGW (gcc 4.8.1, gdb 7.6.1) separately (See «How to install MinGW»), and configured the compiler’s and debugger’s path to the installed MinGW as in the above step.

        Alternatively, consider using Eclipse or Netbeans with Cygwin or MinGW GNU GCC compiler.

        Writing C/C++ Programs in CodeBlocks
        1. CodeBlocks’ Wiki @ http://wiki.codeblocks.org/index.php?title=Main_Page, in particular, «Creating a new project» and «Debug my Program».
        Writing Toy Programs (without Creating a Project)

        To write toy programs (such as few-line simple programming exercises):

        1. File ⇒ New ⇒ Empty File.
        2. Enter (copy and paste) the following codes: Save the file as » Hello.cpp » in your project directory (e.g., » d:\project «).
        3. Build (Compile and Link): Select «Build» menu ⇒ Build (Ctrl-F9).
        4. Run: Select «Build» menu ⇒ Run (Ctrl-F10).

        The drawback is you cannot debug program without creating a project.

        Writing Programs (under Project)

        Other than the few-line toy programs, you shall create a project for each of your application. A project contains related files such as source codes, header files, and relevant resources. Also, under CodeBlocks, you can only debug your program under a project — single-file program (in previous section) debugging is not supported.

        1. File ⇒ New ⇒ Project. ⇒ Console Application ⇒ Go.
        2. The «Console Application» wizard appears:
          1. Next
          2. Select «C++» ⇒ Next.
          3. In «Project Title», enter » HelloProject «. In «Folder to create project in», set to your working directory, e.g., » d:\project «. Accept the default for the rest ⇒ Next.
            A project directory » HelloProject » will be created under » d:\project «, with a project configuration filename of » HelloProject.cbp «. You could later create more projects under this working directory » d:\project «.
          4. In «Compiler» field, accept the defaults of «GNU GCC Compiler» ⇒ Finish.
          1. File ⇒ New File. ⇒ Select C/C++ source or C/C++ header.
          2. C++ ⇒ Next.
          3. In «Filename with full path» ⇒ Click the «Navigate» (. ) button to navigate to the project directory and enter the new file name. Check both the «Debug» and «Release» boxes (or «All») ⇒ Finish.
          Set Active Project

          You can create more projects. However, the «Build» and «Run» commands are always apply to the active project, which is shown in bold. To activate a project: right-click on the project name ⇒ «Activate Project».

          Open an Existing Project

          To open an existing project, either:

          1. From «File» menu ⇒ «Recent Projects» ⇒ Choose the desired project; or
          2. From «File» menu ⇒ «Open. » ⇒ Navigate to your project directory ⇒ Choose » ProjectName .cbp «, where «.cbp» stands for CodeBlocks-Project.
          Writing Many Toy Programs under ONE Project

          Although a project may contain many source files, there can only be one main() function among all the source files. That is, you cannot keep two toy programs (each having a main() function) in one project (you will get the error «multiple definition of ‘main’» when you try to build the project). You need to create one project for each toy program. This is clumsy!

          Codeblock, nonetheless, allow you to add files or remove files from a project. The removed files are not deleted and remain in the folder. We could use this feature to write many toy programs under one project. The procedures are as follows:

          1. Create a C/C++ project called «ToyProgramProject» (read previous section on how to create a project). You shall get a » main.cpp » automatically.
          2. Write your toy program on » main.cpp «. Build and run the program.
          3. To write another program: select «File» ⇒ «Save File as» ⇒ enter a program name such as » myfirst.cpp «. Remove it from the project (because each project can only have one file with main() ), by right-click on » myfirst .cpp » ⇒ «remove file from project».
          4. Continue to write your second toy program on » main.cpp «. Build and run.
          5. Repeat Step 3 and 4 for another toy program.
          6. Suppose that you wish to run » myfirst.cpp » again: First remove » main.cpp » from the project. Right-click on the project ⇒ Add File. ⇒ Choose » myfirst.cpp » ⇒ Open ⇒ Check both the «Debug» and «Release» box ⇒ OK. You can now build and run the » myfirst.cpp «.

          In brief, use the «Add File» and «Remove File» to place your desired toy program file (with the main() function) under the active project. You can then «Build» the project and «Run» your toy program.

          CodeBlocks’ Common Errors
          Cannot Compile any C/C++ Program after Installing CodeBlocks
          1. You downloaded the CodeBlocks with «MinGW GNU C/C++ Compiler» (e.g., » codeblocks-10.05mingw-setup.exe «).
          2. Goto «Settings» menu ⇒ «Compiler. » ⇒ Select tab «Toolchain Executables» ⇒ Check the «Compiler’s Installation Directory». It shall be set to the «MinGW» sub-directory of the CodeBlocks installation directory, e.g., » c:\Program Files\codeblocks\MinGW » suppose that CodeBlocks is installed in » c:\Program Files\codeblocks «.
          Cannot Build or Run Program — Build/Run Buttons and Menu-Items are Grey and Not Selectable

          A previous program is still running. You need to terminate the program by closing the output console window.

          Error: undefined reference to `WinMain@16′

          Check that you have a main() function in your function. Check your spelling of main !

          (For C Programs) System Error: «xxx.exe has stopped working»

          Check your scanf() function. You probably omitted the ‘&’ before the variable name.

          Debugging C/C++ Program in CodeBlocks

          Able to use a graphics debugger to debug program is crucial in programming. It could save you countless of hours guessing on what went wrong.

          Step 0: Write a C++ Program

          Follow the steps in «Writing C++ Program (with Project)» to write the following C++ program, to be used for the debugging practice. This program computes and prints the factorial of n ( =1*2*3*. *n ). The program, however, has a logical error and produce a wrong answer for n=20 . (It outputs «The Factorial of 20 is -2102132736» — a negative number?!).

          Run the program and observe the output produced:

          Let’s use the graphic debugger to debug the program.

          Step 1: Set an Initial Breakpoint

          Set an initial breakpoint at main() function by clicking on the «left-margin» (right-side of the line number) of the line containing main() . A red circle appears indicating a breakpoint has been set at that line. A breakpoint suspends program execution for you to examine the internal states.

          Step 2: Start Debugging

          From «Debug» menu, select «Start (F8)». The program begins execution but suspends its execution at the breakpoint, i.e., main() . An yellow arrow (as shown in the diagram) appears and points at the main() , indicating this is the next statement to be executed.

          Step 3: Single-Step and Watch the Variables and Outputs

          Click the «Debugging Windows» button on the «Debug» toolbar and select «Watches» to enable the «Watch» pane. (You could also do it from the «Debug» menu.)

          Click the «Next line» button on the «Debug» toolbar to single-step thru your program. At each of the step, you could examine the internal state of your program, such as the value of the variables (in the «Watches» pane), the outputs produced by your program (in the console), etc.

          Single-stepping thru the program and watching the values of the variables and the outputs produced is the ultimate mean in debugging programs — because it is exactly how the computer runs your program!

          Step 4: Breakpoint, Run-To-Cursor, Continue and Stop

          As mentioned, a breakpoint suspends program execution and let you examine the internal states of the program. To set a breakpoint on a particular line, click the left-margin of that line (or select «Toggle Breakpoint (F5)» from «Debug» menu).

          The «Continue» resumes the program execution, up to the next breakpoint, or till the end of the program.

          Single-stepping thru a loop with a large count is time-consuming. You could set a breakpoint at the statement immediately outside the loop (e.g., Line 12 of the above program), and issue «Continue» to complete the loop.

          Alternatively, you can place the cursor on a particular line, right-click and select «Run-To-Cursor» to resume execution up to this line.

          The «Stop» ends the debugging session. Always terminate your current debugging session using «Stop» or «Continue» till the end of the program.

          Important: I can’s stress more that mastering the use of debugger is crucial in programming. Explore the features provided by the debuggers.

          Other Debugging Features

          Step-Into and Step-Out: To debug a function, you need to use «Step-Into» to step into the first statement of the function. («Step-Over» runs the function in a single step without stepping through the statements inside the function.) You could use «Step-Out» to return to the caller, anywhere within the function. Alternatively, you can set a breakpoint inside a function.

          Watching a Variable: To add a variable into the «Watches» panel, goto «Debug» ⇒ «Edit Watch. » ⇒ «Add» ⇒ Enter the variable name ⇒ You can select the format, or «watch as array».

          Tips and Tweaks
          1. Re-format Source Code: Right-click on the source file ⇒ Format this file (AStyle). [Source formatting feature is provided by a plugin called AStyle, which can be accessed via menu «Plugins» ⇒ «Source Code Formatter (AStyle)». To configure the formatting styles, goto «Settings» ⇒ «Editor. » ⇒ «Source Formatter».]
          2. Auto-Complete: type the initial letters of a keyword/identifier and press Ctrl-space to list the available options.
          3. Abbreviation: e.g., type «for» and press control-J to get the skeleton of for-loop. The abbreviation list can be configured in «Settings» menu ⇒ «Editor. » ⇒ «Abbreviations».
          4. Zoom in/out on Editor Panel: Either:
            1. From «Edit» menu ⇒ «Special Commands» ⇒ «Zoom» ⇒ «In», «Out», or «Reset», or
            2. Hold the control key and zoom in/out via the mouse scroll wheel, or
            3. Use keyboard shortcut: control number-pad + (zoom in), control number-pad / (zoom out).
            1. Source Formatter: You can choose the «Java» style.
            2. [TODO] more
            1. CodeBlocks Mother Site @ http://www.codeblocks.org/.
            2. CodeBlocks’ Wiki @ http://wiki.codeblocks.org/index.php?title=Main_Page.
            3. CodeBlocks’ User Manual @ http://www.codeblocks.org/user-manual.

            Latest version tested: CodeBlocks 13.12
            Last modified: February, 2014

            Среда разработки CodeBlocks. Установка

            Adding compiler to code::blocks

            enter image description hereFrom here I’ve downloaded newest release of GCC, namely 4.6.
            How can I add this compiler to my code::blocks?

            1 Answer 1

            Go to the Settings menu and hit Compiler and Debugger:

            enter image description here

            Go to Copy, and name the new compiler GCC 4.6 or whatever you’d like. Go to the Toolchain Executables tab, and fill in the directory name. I think all of the .exe’s should be named the same thing. Make sure and copy paste your linker settings from one to the other. Now that compiler title will appear in all of the dialog boxes. I’m not entirely sure how to move the new one up the list so it’s the default.

            Читать:
            Какой шрифт использует ютуб

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