Что такое gcc в linux
Перейти к содержимому

Что такое gcc в linux

  • автор:

GCC Linux C compiler and C language hello world programs

The Linux gcc command is a C language complier that is right there to work with if one wants to get into C programing in a Linux system. I took a moment to start playing around with it, and just have some fun with a few quick, basic, C language hello world programs.

I am very much a javaScript developer, and as such I have been shying away from C for a long time. There is much about the language that strikes me as being very intense and time consuming. In javaScipt I like having things going on like garbage collection, and dynamic typing. Sure javaScript is like riding a bike with training wheels, but it is still very much a bike that will take me places. I have this mindset that what matters most in programing are things that are independent of language. Regardless if a program is written in javaScript, C, or even something like qBasic what does the program do? Why would I or anyone else want to use it? The answers to those questions are what matter first and for most to me.

However getting back to the topic at hand. I want to start experimenting with at least a few languages outside of javaScript, I still like the language a lot, it is still my preferred language by far, however I want to expand at least a little way into some other languages. With that said C has been on my scope for a long time, and I thought that it could not hurt to work out at least a few quick hello world C examples that I would then build using the Linux gcc command. So lets get to it then.

1 — Linux gcc and C Hello World

In this section I will be going over a very basic Hello world C language source code file called hello.c. This source code file is just a very simple typically hello world program that will just print Hello World to the standard output of the console. I then also worked out a simple bash script that will use gcc to build the hello.c file into a binary called just simply hello. I can then run the binary in the bash shell and get the expected result.

When it comes to learning any language one has to start somewhere, and this type of program is just that.

1.1 — The hello.c file

Here is the source code that I cam up with by just searching for a simple C language hello world program. It makes use of just one library called stdio.h which provides the printf function along with many other useful basic tools when it comes to working with standard output.

1.2 — The build.sh script

I then made a simple bash script that when called should build the hello.c file into a binary called just hello. In Linux systems binaries often seem to have no file name extension like that.

1.3 — Building my first C Programe with gcc

So when I run my build.sh script gcc compiles by hello.c into a hello binary. When I call my hello binary i end up getting the expected result in my console.

Well that was fun actually, it may just be a hello world program but it was fun to build a very simple yet functioning C binary. I should take a moment to look into making at least a few more C examples though, maybe sticking to what there is to work with in the stdio.h lib. Maybe even touch base on a few other features of gcc in the process, if I get to it.

2 — Printing an init value, and an improved build.sh

I should take at least one or two more steps beyond just a simple hello world example with this, just printing hello world to the console alone is not a good stopping point for me at least. I may or may not get into writing a collection of posts on C programing, but without even going that far there is the question of what the next step is from hello world. For me it seems like that next step is how to go about printing a number rather than a string to the console.

In javaScript doing so is just as simple as printing a string more or less, javaScript is a typeless language after all. However that is not the case with c of course I can not just pass an int for a parameter of a function where a string is what is expected.

2.1 — The print_int.c file

With C I am dealing with string typing, and with that said I can not just pass a number for an argument where a string is expected. Still doing so is not at all that much harder, in fact I can use the same printf method to do so by passing the init as a second argument and then using a pattern in the string that I pass as the first.

2.2 — Improved build.sh

For this example I made an improved build.sh script that will work not just with this source file, but any file that I want to build with gcc. With this script I am just making it so I can give one argument to the script that is the name of the C source file that I want to build. I am then also using the Linux cut command to just cut the file extension off the end of the file name to produce a name for the output file to create with Linux gcc.

2.3 — Looking good

So this example seems to work as it should for me also. The source file builds without any problems with gcc, and when I run the resulting binary I get the number printed out to the standard output.

So now I have worked out how to just print a string to the console, and now a number. The process is not so hard of course I can just stick to using just this one simple library that can eb used to just print things out to the standard output. There are a few more basic things that come to mind though that I should get to with this post, so lets look at some of the other methods in this basic c library.

3 — Fopen example

In the stdio there are also some basic functions for opening, writing to, and closing files. There is the fopen function, followed by fputs, and fclose to work with. These methods can be used to create a very basic hello world example that creates a file rather than spiting something out to the command line.

Once again I just need to use gcc to create a little binary, and then it does just what I thought it would.

These very simple hello world style C programs where fun. For someone that has been working with C for years, or decades even now these are of course trivial. However for me this is pretty cool coming from an experience where I have only been playing around with javaScript thus far.

4 — Conclusion

So this was fun to take a moment to play around with gcc for a little while. I was wondering to myself how hard could it be to just cerate a few very basic hello world style examples with the C language and build them with gcc? As I expected it was not so hard to do that at least when it comes to just some very simple examples.

The next step from here is to maybe start a collection of a few posts on creating a few simple programs written in C and compiled with gcc. I might get around to doing that at some point, if so I am sure I will end up editing, and expanding this post as needed. So far I have wrote just one more c code example for another post on the linux test command. In that post I made a simple c program that will check a given folder for markdown files and if one or more files are in there the program will end with a status of zero, else it will end with a non zero exit code status.

GCC, the GNU Compiler Collection

The GNU Compiler Collection includes front ends for C, C++, Objective-C, Fortran, Ada, Go, and D, as well as libraries for these languages (libstdc++. ). GCC was originally written as the compiler for the GNU operating system. The GNU system was developed to be 100% free software, free in the sense that it respects the user’s freedom.

We strive to provide regular, high quality releases, which we want to work well on a variety of native and cross targets (including GNU/Linux), and encourage everyone to contribute changes or help testing GCC. Our sources are readily and freely available via Git and weekly snapshots.

Major decisions about GCC are made by the steering committee, guided by the mission statement.

Supported Releases

Get our announcements

Donate to GNU Toolchain Fund

Copyright (C) Free Software Foundation, Inc. Verbatim copying and distribution of this entire article is permitted in any medium, provided this notice is preserved.

Unix как IDE: Компиляция

Под Unix существует множество компиляторов и интерпретаторов, но здесь мы будем обсуждать лишь gcc как средство компиляции C-кода, и коротко коснемся использования perl в качестве примера интерпретатора.

GCC — это набор компиляторов, обладающий очень почтенным возрастом и распространяемый под лицензией GPL. Он известен как инструмент работы с программами на C и C++. Свободная лицензия и повсеместная распространенность на Unix-подобных системах стали залогом его неизменной популярности, хотя есть и более современные альтернативы, использующие инфраструктуру LLVM, такие как Clang.

Основной исполняемый файл gcc лучше представлять не как компилятор в привычном понимании, а слой абстракции над множеством отдельных инструментов программирования, выполняющих парсинг кода, компиляцию, линковку и другие действия. Это значит, что с его помощью можно не просто получить работающий бинарник из кода на C, но детально исследовать все шаги этого сложного процесса, и при необходимости подстроить его под свои нужды.

Здесь я не буду обсуждать использование make-файлов, хотя они наверняка понадобятся для любого проекта сложнее, чем в один файл. Make-файлов я коснусь в следующей статье о средствах автоматизации сборки.

Компиляция и сборка объектного кода

Объектный код компилируется вот такой командой:

Если код верен, будет создан нелинкованный двоичный объектный файл под именем example.o в текущей папке, или выведены сообщения о проблемах. Заглянуть внутрь полученного файла и увидеть его содержимое на языке ассемблера можно так:

Как вариант, можно попросить gcc сразу показать итоговый ассемблерный код при помощи параметра -S:

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

Препроцессор

Препроцессор C (cpp) обычно используется для подключения заголовочных файлов и определения макросов. Это стандартная часть процесса компиляции gcc, но можно просмотреть генерируемый им код, вызвав cpp напрямую:

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

Связывание объектов

Один или несколько объектных файлов могут быть связаны в соответствующий исполняемый файл:

В этом примере gcc просто вызывает ld, линковщик GNU. Команда создаст исполняемый файл по имени example .

Компиляция, сборка и связывание

Все вышеперечисленное может быть выполнено в один шаг при помощи команды:

Этот способ проще, но компиляция объектов по отдельности дает некоторый выигрыш в производительности: не нужно компилировать не изменявшийся код, но об этом мы поговорим в следующей статье.

Включение внешних файлов и связывание

Файлы C и заголовочные файлы могу быть явно включены в компиляцию при помощи параметра -l:

Аналогично, если код нужно динамически связать с уже скомпилированной системной библиотекой, доступной в одной из системных папок ( /lib или /usr/lib ), например, ncurses, этого можно добиться использованием ключа -l:

Если в процессе компиляции внешних связей много, имеет смысл внести их в переменные окружения:

Кстати, Makefile затем и создан, чтобы избавить нас от беспокойства о таких мелочах.

План компиляции

Чтобы посмотреть подробности внутренней кухни gcc, можно добавить ключ -v, и план компиляции будет выведен в стандартный поток вывода ошибок:

Если нет нужды генерировать объектные или исполняемые файлы, то для аккуратности можно использовать -###:

Очень полезно посмотреть, какие действия gcc предпринимает без нашего ведома, кроме того, так мы можем выявить нежелательные шаги при компиляции.

Расширенный вывод сообщений об ошибках

Существует возможность добавить ключи -Wall и/или -pedantic, чтобы gcc предупреждал нас о случаях, которые не обязательно являются ошибками, но могут ими быть:

Удобно включать такие опции в Makefile или в определении makeprg для Vim, так как они отлично сочетаются с окном quickfix, и помогают писать читабельный, совместимый и безошибочный код.

Профилирование процесса компиляции

Вы можете включить опцию -time, чтобы gcc отображал в тексте вывода время выполения каждого из шагов:

Оптимизация

Gcc имеет ключи оптимизации, указав которые можно попросить его создавать более эффективный объектный код и связанные бинарники за счет увеличения времени компиляции. Я считаю -O2 золотой серединой для выпускаемого кода:

Подобно любой команде Bash, все это можно вызывать прямо из Vim:

Интерпретаторы

Подход к интерпретируемому коду в Unix-системах иной. В своих примерах я буду использовать Perl, но те же принципы применимы для кода, например, на Python или Ruby.

Inline-код

Можно строку Perl-кода прямо на исполнение интерпретатору любым из перечисленных ниже способов Первый, наверное, самый простой и общеупотребительный способ работы с Perl; второй использует синтаксис heredoc, а третий — это классический конвейер Unix.

Конечно, в будничной жизни мы храним код в файле, который можно вызвать прямо вот так:

Можно проверить синтаксис кода без его выполнения с помощью ключа -c:

Порой хочется использовать скрипт подобно любому исполняемому бинарнику, не беспокоясь о том, что он из себя представляет. Для этого в скрипт добавляют первой строкой так называемый «shebang«, указывающий путь к интерпретатору, которому следует передать на исполнение данный файл.

Скрипту после этого можно ставить атрибут исполняемого файла вызовом chmod. Также хорошим тоном считается переименовать файл, убрав расширения, поскольку он теперь считается почти настоящим исполняемым файлом:

Затем файл можно вызывать напрямую, без указания интерпретатора:

Вся эта кухня так здорово работает, что многие стандартные утилиты Linux-систем, такие как adduser, в действительности являются скриптами на Perl или Python.

В следующей публикации я расскажу о методах работы с make для сборки проектов, сравнимых с привычными IDE.

What is gcc in linux ?

Iheb Yahyaoui

In Linux, the GCC stands for GNU Compiler Collection. It is a compiler system for the various programming languages. It is mainly used to compile the C and C++ programs.

First of all let’s create a file containing a c program named main.c as shown above.

Basic compilation :

For basic compilation, gcc works as :

This command will produce an output file named a.out by default.

Provide an output file name :

To provide a file name for the output file we should be using -o option.

This command will produce an output file named main.

Generate a preprocessed file :

If an intermediary output after the preprocessing stage is required then use the -E option.

The command above would produce a preprocessed output on stdout. The output can be redirected into a file to save it.

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

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