- команда gcc в Linux с примерами
- GCC C Compiler
- GCC syntax
- GCC options
- GCC examples
- Shared libraries with GCC on Linux
- Step 1: Compiling with Position Independent Code
- Step 2: Creating a shared library from an object file
- Step 3: Linking with a shared library
- Telling GCC where to find the shared library
- Step 4: Making the library available at runtime
- Using LD_LIBRARY_PATH
- Using rpath
- rpath vs. LD_LIBRARY_PATH
- Using ldconfig to modify ld.so
- GCC Command in Linux
- Introduction to GCC Command in Linux
- GCC Options in Linux Environment
- Step 1: Write a C Program
- Step 2: Compile the C Program
- Step 3: Run the C Program
- Conclusion
- Recommended Articles
команда gcc в Linux с примерами
GCC означает GNU Compiler Collections, которая используется для компиляции в основном языка C и C ++. Он также может быть использован для компиляции Objective C и Objective C ++. Наиболее важной опцией, требуемой при компиляции файла исходного кода, является имя исходной программы, остальные аргументы необязательны, такие как предупреждение, отладка, компоновка библиотек, объектный файл и т. Д. Различные параметры команды gcc позволяют пользователю остановить компиляцию Процесс на разных этапах.
Синтаксис:
Пример: это скомпилирует файл source.c и выдаст выходной файл как файл.out, который является именем по умолчанию для выходного файла, заданного компилятором gcc, который может быть выполнен с использованием ./a.out
Наиболее полезные опции с примерами: Здесь source.c — это файл кода программы C.
- -o opt: это скомпилирует файл source.c, но вместо того, чтобы дать имя по умолчанию, следовательно, выполненное с помощью ./opt , он выдаст выходной файл как opt. -o для опции выходного файла.
-Werror: Это скомпилирует источник и покажет предупреждение, если в программе есть какая-либо ошибка, -W для выдачи предупреждений.
-Wall: при этом будут проверяться не только ошибки, но и предупреждения всех видов, например ошибки неиспользуемых переменных. Рекомендуется использовать этот флаг при компиляции кода.
-ggdb3: эта команда дает нам права на отладку программы с использованием gdb, которая будет описана позже, опция -g предназначена для отладки.
-lm: эта команда связывает библиотеку math.h с нашим исходным файлом, опция -l используется для связывания конкретной библиотеки, для math.h мы используем -lm.
-std = c11: эта команда будет использовать версию стандартов c11 для компиляции программы source.c , которая позволяет определять переменные при инициализации цикла, также с использованием более новой версии стандартов.
-c: эта команда компилирует программу и передает объектный файл в качестве вывода, который используется для создания библиотек.
-v: эта опция используется для подробной цели.
Источник
GCC C Compiler
GCC is a short of GNU Compiler Collection, a C compiler for Linux.
GCC syntax
$ gcc [options] [source files] [object files] [-o output file]
GCC options
GCC main options:
option | description |
---|---|
gcc -c | compile source files to object files without linking |
gcc -Dname[=value] | define a preprocessor macro |
gcc -fPIC | generate position independent code for shared libraries |
gcc -glevel | generate debug information to be used by GDB |
gcc -Idir | add include directory of header files |
gcc -llib | link with library file |
gcc -Ldir | look in directory for library files |
gcc -o output file | write build output to output file |
gcc -Olevel | optimize for code size and execution time |
gcc -shared | generate shared object file for shared library |
gcc -Uname | undefine a preprocessor macro |
gcc -w | disable all warning messages |
gcc -Wall | enable all warning messages |
gcc -Wextra | enable extra warning messages |
GCC examples
Compile file1.c and file2.c and link to output file execfile:
$ gcc file1.c file2.c -o execfile
Run output file execfile:
Compile file1.c and file2.c without linking:
$ gcc -c file1.c file2.c
Compile myfile.c with debug information and link to output file execfile:
$ gcc -g myfile.c -o execfile
Compile myfile.c with warning messages enabled and link to output file execfile:
$ gcc -Wall myfile.c -o execfile
Compile myfile.c with and link with static library libmath.a located in /user/local/math to output file execfile:
$ gcc -static myfile.c -L/user/local/math -lmath -o execfile
Источник
Shared libraries with GCC on Linux
Libraries are an indispensable tool for any programmer. They are pre-existing code that is compiled and ready for you to use. They often provide generic functionality, like linked lists or binary trees that can hold any data, or specific functionality like an interface to a database server such as MySQL.
Most larger software projects will contain several components, some of which you may find use for later on in some other project, or that you just want to separate out for organizational purposes. When you have a reusable or logically distinct set of functions, it is helpful to build a library from it so that you do not have to copy the source code into your current project and recompile it all the time — and so you can keep different modules of your program disjoint and change one without affecting others. Once it is been written and tested, you can safely reuse it over and over again, saving the time and hassle of building it into your project every time.
Building static libraries is fairly simple, and since we rarely get questions on them, I will not cover them. I will stick with shared libraries, which seem to be more confusing for most people.
Before we get started, it might help to get a quick rundown of everything that happens from source code to running program:
- C Preprocessor: This stage processes all the preprocessor directives. Basically, any line that starts with a #, such as #define and #include.
- Compilation Proper: Once the source file has been preprocessed, the result is then compiled. Since many people refer to the entire build process as compilation, this stage is often referred to as compilation proper. This stage turns a .c file into an .o (object) file.
- Linking: Here is where all of the object files and any libraries are linked together to make your final program. Note that for static libraries, the actual library is placed in your final program, while for shared libraries, only a reference to the library is placed inside. Now you have a complete program that is ready to run. You launch it from the shell, and the program is handed off to the loader.
- Loading: This stage happens when your program starts up. Your program is scanned for references to shared libraries. Any references found are resolved and the libraries are mapped into your program.
Steps 3 and 4 are where the magic (and confusion) happens with shared libraries.
Now, on to our (very simple) example.
foo.h defines the interface to our library, a single function, foo(). foo.c contains the implementation of that function, and main.c is a driver program that uses our library.
For the purposes of this example, everything will happen in /home/username/foo
Step 1: Compiling with Position Independent Code
We need to compile our library source code into position-independent code (PIC): 1
Step 2: Creating a shared library from an object file
Now we need to actually turn this object file into a shared library. We will call it libfoo.so:
Step 3: Linking with a shared library
As you can see, that was actually pretty easy. We have a shared library. Let us compile our main.c and link it with libfoo. We will call our final program test. Note that the -lfoo option is not looking for foo.o, but libfoo.so. GCC assumes that all libraries start with lib and end with .so or .a (.so is for shared object or shared libraries, and .a is for archive, or statically linked libraries).
Telling GCC where to find the shared library
Uh-oh! The linker does not know where to find libfoo. GCC has a list of places it looks by default, but our directory is not in that list. 2 We need to tell GCC where to find libfoo.so. We will do that with the -L option. In this example, we will use the current directory, /home/username/foo:
Step 4: Making the library available at runtime
Good, no errors. Now let us run our program:
Oh no! The loader cannot find the shared library. 3 We did not install it in a standard location, so we need to give the loader a little help. We have a couple of options: we can use the environment variable LD_LIBRARY_PATH for this, or rpath. Let us take a look first at LD_LIBRARY_PATH:
Using LD_LIBRARY_PATH
There is nothing in there. Let us fix that by prepending our working directory to the existing LD_LIBRARY_PATH:
What happened? Our directory is in LD_LIBRARY_PATH, but we did not export it. In Linux, if you do not export the changes to an environment variable, they will not be inherited by the child processes. The loader and our test program did not inherit the changes we made. Thankfully, the fix is easy:
Good, it worked! LD_LIBRARY_PATH is great for quick tests and for systems on which you do not have admin privileges. As a downside, however, exporting the LD_LIBRARY_PATH variable means it may cause problems with other programs you run that also rely on LD_LIBRARY_PATH if you do not reset it to its previous state when you are done.
Using rpath
Now let s try rpath (first we will clear LD_LIBRARY_PATH to ensure it is rpath that is finding our library). Rpath, or the run path, is a way of embedding the location of shared libraries in the executable itself, instead of relying on default locations or environment variables. We do this during the linking stage. Notice the lengthy “-Wl,-rpath=/home/username/foo” option. The -Wl portion sends comma-separated options to the linker, so we tell it to send the -rpath option to the linker with our working directory.
Excellent, it worked. The rpath method is great because each program gets to list its shared library locations independently, so there are no issues with different programs looking in the wrong paths like there were for LD_LIBRARY_PATH.
rpath vs. LD_LIBRARY_PATH
There are a few downsides to rpath, however. First, it requires that shared libraries be installed in a fixed location so that all users of your program will have access to those libraries in those locations. That means less flexibility in system configuration. Second, if that library refers to a NFS mount or other network drive, you may experience undesirable delays — or worse — on program startup.
Using ldconfig to modify ld.so
What if we want to install our library so everybody on the system can use it? For that, you will need admin privileges. You will need this for two reasons: first, to put the library in a standard location, probably /usr/lib or /usr/local/lib, which normal users do not have write access to. Second, you will need to modify the ld.so config file and cache. As root, do the following:
Now the file is in a standard location, with correct permissions, readable by everybody. We need to tell the loader it is available for use, so let us update the cache:
That should create a link to our shared library and update the cache so it is available for immediate use. Let us double check:
Now our library is installed. Before we test it, we have to clean up a few things:
Clear our LD_LIBRARY_PATH once more, just in case:
Re-link our executable. Notice we do not need the -L option since our library is stored in a default location and we are not using the rpath option:
Let us make sure we are using the /usr/lib instance of our library using ldd:
Good, now let us run it:
That about wraps it up. We have covered how to build a shared library, how to link with it, and how to resolve the most common loader issues with shared libraries — as well as the positives and negatives of different approaches.
- It looks in the DT_RPATH section of the executable, unless there is a DT_RUNPATH section.
- It looks in LD_LIBRARY_PATH. This is skipped if the executable is setuid/setgid for security reasons.
- It looks in the DT_RUNPATH section of the executable unless the setuid/setgid bits are set (for security reasons).
- It looks in the cache file /etc/ld/so/cache (disabled with the -z nodeflib linker option).
- It looks in the default directories /lib then /usr/lib (disabled with the -z nodeflib linker option).
What is position independent code? PIC is code that works no matter where in memory it is placed. Because several different programs can all use one instance of your shared library, the library cannot store things at fixed addresses, since the location of that library in memory will vary from program to program. ↩
GCC first searches for libraries in /usr/local/lib, then in /usr/lib. Following that, it searches for libraries in the directories specified by the -L parameter, in the order specified on the command line. ↩
Источник
GCC Command in Linux
By Priya Pedamkar
Introduction to GCC Command in Linux
In this article we will see an outline on GCC Command in Linux, GCC is abbreviated as GNU Complier Collection. GCC can compile C, C++, Ada and many more programming languages which are understandable by the system. As Linux is open source and free OS, it has become very popular among all the programmers. So to compile programming languages in Linux, GCC is used. GCC can help us to write and execute C language in Linux with a more advanced way.
To check the default version of gcc compiler in your system, you can use the command as –version in your Linux command prompt.
Web development, programming languages, Software testing & others
Basic GCC Syntax
gcc [options] [source_file] [object_files] [-o output_file]
Let us take a simple C program and execute in Linux with the help of Linux.
To Execute a C program, we need to follow three steps. They are:
- Write: C Program for which you want to compile in Linux environment.
- Compile: Program to check if any error exists or not.
- Run: Program to see the output in Linux environment.
The above steps are elaborated with examples and syntax below:
GCC Options in Linux Environment
Here are the few options given to use while compiling different programming languages in Linux. We have also explicitly used these options below to compile a C Program below.
Options | Description |
Gcc –c | Compiles source files to object files without linking to any other object files. |
gcc –Idir | Includes the directories of header files |
gcc –llib | link the code with the library files |
gcc -o output file | Build the output generated to output file |
gcc –w | Disables all warning messages during the compilation. |
gcc –Wall | enables all warning messages during the compilation |
gcc –Wextra | Enables extra warning messages during the compilation. |
Step 1: Write a C Program
Create a C program to print “Hello World” in Linux by following the below steps. Make sure you save the C program with .c as its extension. The below steps are to create a .c file and write the code in it. Save before you close the file.
- touch main.c
- vi main.c
- write the below code:
#include
int main(void)
<
printf(«\n Hello World \n»);
return 0;
>
- save the code in linux
Step 2: Compile the C Program
Now below are the options to compile a simple C program using GCC in Linux. You can use the options as per your requirement and build your program to get desired output.
1. The basic syntax to compile a C code is: To compile a C Code, use the below syntax. This syntax is used without any options.
Syntax: gcc main.c
When you compile the above code, you will get the output with the filename as a.out. The default output after compiling the C Program is resulted in”a.exe” or “a.out” format.
2. We can also specify explicitly mention the output file name by using –o as an option.
Syntax: gcc main.c –o output
3. To see the warnings while we compile a C program: we need to use an option –wall while compiling the C Program as below:
Example:
#include
int main(void)
<
printf(«\n Hello World [%d]\n», i);
return 0;
>
Syntax: gcc –wall main.c –o output
Once we set –wall option, we can see the warnings that can occur in our code. Here our code will give uninitialized warning for the variable “i”.
4. To get preprocessed output with –E option: the output will be produced on stdout to redirect our result in other file. Here output.i would contain the preprocessed result.
Syntax: gcc –E main.c > output.i
5. To get intermediate files using –save-temps: We can store all the intermediate files that are generated during the compilation in the same directory from where we do the compilation.
Syntax: gcc –save-temps main.c
Example: gcc –save-temps main.c
Output: ls
a.out main.c main.i main.o main.s
Here we can see the intermediate and executable files as well.
6. To see the error while compiling the C Program: To see the error during the compilation of C Program, we can use the option –W. This is one of the best practices to use to avoid errors.
Syntax: gcc main.c –Werror –o output
7. To debug C Program in Linux: To debug C Program in Linux during compilation can be done by using –ggdb.
Syntax: gcc –ggdb main.c –wall –o output
8. Verbose option is to see the complete description used in Linux during the compilation. The command –v is used as below:
Syntax: gcc –v main.c –o output
Step 3: Run the C Program
The final step is to run the C program in Linux OS by using the below syntax:
Syntax: ./program_name
In our example, we can run our program by using below syntax:
Syntax: ./output
Output: Hello World
Conclusion
Here in this article, we came to know about how to Write a C Program in Linux, Compile the C Program and Run the c Program. GCC is very easy to use and has given us many options to simplify or run the C Program in Linux OS. Make sure all the packages are installed in Linux and then you can run C, C++, Ada and many more languages in Linux.
Recommended Articles
This has been a guide to GCC Command in Linux. Here we have discussed introduction to GCC Command in Linux, GCC option in Linux Environment with appropriate example. You may also have a look at the following articles to learn more –
Linux Training Program (16 Courses, 3+ Projects)
Источник