As a beginner on programming, it’s better to use GCC to compile the program. Then you can know more about the
process of a program compile and link. I advice you to using vi/vim to edit the code.
GCC provide so many command option. However, you don’t have to learn all the option. As a beginner, you only need
to be familiar with several option. Then you can begin to write your program.
- Common compiler command options
For example, the source file is test.c
(1). Compile and link with no option
<font color="rgb(88, 88, 88)"><font face="Arial, Helvetica, sans-serif"><font style="font-size: 13px">#gcc test.c</font></font></font>
Function: pretreatment, assemble, compile and link to an executable program.There is no output specified. “a.out” is
the default output file. After compiling successfully ,there will be a new file “a.out” in the current path. You can execute
the command to run the program.
<font color="rgb(88, 88, 88)"><font face="Arial, Helvetica, sans-serif"><font style="font-size: 13px">#./a.out</font></font></font>
(2). Option -o
<font color="rgb(88, 88, 88)"><font face="Arial, Helvetica, sans-serif"><font style="font-size: 13px">#gcc test.c -o test</font></font></font>
Function: pretreatment, assemble, compile and link to an executable program. The “-o” option is used to specify
the output file. After compiling successfully , there will be a new file “test” in the current path. You can execute the
command to run the program.
#./test
(3). Option -E
#gcc -E test.c -o test.i
Fuction: pretreatment the “test.c” and assemble to “test.s”.
(5). Option -c
#gcc -c test.s
Function: compile the “test.s” to “test.o”
(6). Option -o
#gcc test.o -o test
Function: link “test.o” to “test”
(7). Option -O
#gcc -O1 test.c -o test
Using the level 1 to compile the file. The levels are 1 to 3. Higher level with
(8). Compile the C++ program file using the std libs..
#gcc test.cpp -o test -lstdc++
Function: compile the test.cpp and link to test execute file. -lstdc++ means the std libs.
- Compile more than one files.
If you want to compile more than one files. You can do it as the follow ways:
For example, you are going to compile these two files test.c and testfun.c
(1). Compile all files at once.
#gcc testfunc.c test.c -o test
Function: compile the testfun.c and test.c, link to an executive file.
(2). Compile the files respectively and link them to an output file.
#gcc -c testfun.c //compile testfun.c to testfun.o
#gcc -c test.c //compile test.c to test.o
#gcc -o testfun.o test.o -o test // link testfun.o and test.o to test file.
Comparing the two ways above, the fist way need to compile all files at every compile. The second way just compile
the files that have been modified, so it don’t have to compile all files at every compile.