Home Closet GNU Compiler Collection, first steps

GNU Compiler Collection, first steps

by admin

This article is meant to introduce the GNU tools, especially the GCC compiler, to novice nix developers with simple examples.
This is how we will create a simple program. Basically, everything is as usual. We start a special folder in which the project will be placed.
Create there a file named : hello.c
Open the file with any text editor and write a simple code :
#include <stdio.h>
int main(void)
{
printf("Hello world!");
return(0);
}

Save the file and run the command : gcc hello.c
In the folder we created we have a new file – a.out, this name is assigned by default, if not specified otherwise.
This is an executable file. Let’s try to run it by typing : /a.out
And rejoice in connection with the first program written in linux!
Let’s go on. When we start an executable, if we only give it a name, the system will look for it in /usr/bin and /usr/local/bin and, of course, it will not find it. The first of them is designed to contain stable versions of programs, usually included in the Linux distribution. The second is for programs installed by the user (for which nobody is responsible for their stability). By default, programs are installed in the /usr/local/bin directory.
Flags used in compilation
Flag -o flag is used to give a specific name to the resulting executable : gcc hello.c-o say_hello
Flag -E flag is used to see what we get after the preprocessor works. This flag stops program execution, just at the preprocessor stage. The result is a source code file that contains the contents of the header files.
Pull up/see : gcc -E hello.c -o hello.cpp
Flag -with flag is used to create object files (analog of *.obj): gcc -c kalkul.c
The name of the resulting file is the same, but the compiler changes the extension c to o (but you can also specify manually).
Flag -x flag is used when creating an object file from preprocessed source code (like the one we have above), we must make sure to explicitly specify that the file being compiled is a preprocessed source code file which has preprocessor tags. Otherwise it will be handled as a normal C++ file without the preprocessor tags, which means no connection will be established with declared functions.
The C++ file processed by the preprocessor is called cpp-output:
gcc -x cpp-output -c hello.cpp
The project is assembled as follows : gcc hello.o -o say_hello
Launching : /say_hello
What is all this fiddling with intermediate stages for?
Programs rarely consist of a single file. Usually there are several source files and they are combined into a project. In some exceptional cases a program may have to be assembled from several parts possibly written in different languages. In this case it is necessary to run different language compilers, each of them get an object file from its source code and then make these object files into an executable program.

You may also like