?? c-on-unix.html
字號:
<html><head><title>Compiling "C" And "C++" Programs On Unix Systems - gcc/g++</title></head><body><p align=center><img src=http://www.actcom.co.il/~choo/lupg/images/lupg_toolbar.gif height=40 width=360 alt="" usemap="#lupg_map"><map name=lupg_map><area shape=rect coords="3,0 37,39" href=http://www.actcom.co.il/~choo/lupg alt="LUPG home"><area shape=rect coords="67,0 102,39" href=http://www.actcom.co.il/~choo/lupg/tutorials/index.html alt="Tutorials"><area shape=rect coords="138,0 170,39" href=http://www.actcom.co.il/~choo/lupg/related-material.html alt="Related material"><area shape=rect coords="213,0 232,39" href=http://www.actcom.co.il/~choo/lupg/project-ideas/index.html alt="Project Ideas"><area shape=rect coords="272,0 290,39" href=http://www.actcom.co.il/~choo/lupg/essays/index.html alt="Essays"><area shape=rect coords="324,0 355,39" href=mailto:choo@actcom.co.il alt="Send comments"></map><br>[<a href=http://www.actcom.co.il/~choo/lupg/index.html>LUPG Home</a>] [<a href=http://www.actcom.co.il/~choo/lupg/tutorials/index.html>Tutorials</a>] [<a href=http://www.actcom.co.il/~choo/lupg/related-material.html>Related Material</a>] [<a href=http://www.actcom.co.il/~choo/lupg/essays/index.html>Essays</a>] [<a href=http://www.actcom.co.il/~choo/lupg/project-ideas/index.html>Project Ideas</a>] [<a href=mailto:choo@actcom.co.il>Send Comments</a>]<br><img src=http://www.actcom.co.il/~choo/lupg/images/good_bar.gif alt=""></p> v1.0.2<h1>Compiling "C" And "C++" Programs On Unix Systems - gcc/g++</h1>Table Of Contents:<ol><li> <a href="#preface">Preface</a><li> <a href="#single_source_c">Compiling A Single-Source "C" Program</a><li> <a href="#running_the_exe">Running The Resulting Program</a><li> <a href="#debug_info">Creating Debug-Ready Code</a><li> <a href="#optimize">Creating Optimized Code</a><li> <a href="#compiler_warnings">Getting Extra Compiler Warnings</a><li> <a href="#single_source_cpp">Compiling A Single-Source "C++" Program</a><li> <a href="#multi_source_c">Compiling A Multi-Source "C" Program</a><li> <a href="#compilation_steps">Getting a Deeper Understanding - Compilation Steps</a></ol><hr size=4><a name="preface"><font color=brown><h2>Preface - How To Read This Document</h2></font></a><p>This document tries to give the reader basic knowledge in compiling Cand C++ programs on a Unix system. If you've no knowledge as to how tocompile C programs under Unix (for instance, you did that until now onother operating systems), you'd better read this tutorial first, and thenwrite a few programs before you try to get to gdb, makefiles or C libraries.<br><br>If you're already familiar with that, it's recommended to learn about makefiles,and then go and learn other C programming topics and practice the usage ofmakefiles, before going on to read about C libraries. This last issue isonly relevant to larger projects, while makefiles make sense even for a smallprogram composed of but a few source files.</p><p>As a policy, we'll stick with the basic features of programming toolsmentioned here,so that the information will apply to more than a single tool version. This way,you might find the information here useful, even if the system you're usingdoes not have the GNU tools installed.</p><p>In this lovely tutorial, we'll deal with compilation of a C program, usingthe compiler directly from the command line. It might be that you'll eventuallyuse a more sophisticated interface (an IDE - Integrated Development Environment)of some sort, but the common denominator you'll always find is the plaincommand line interface. Further more, even if you use an IDE, it could helpyou understand how things work "behind the scenes". We'll see how to compilea program, how to combine several source files into a single program, howto add debug information and how to optimize code.</p><hr size=4> <a name="single_source_c"><font color=brown><h2>Compiling A Single-Source "C" Program</h2></font></a><p>The easiest case of compilation is when you have all your source code set ina single file. This removes any unnecessary steps of synchronizing several filesor thinking too much. Lets assume there is a file named<a href="single_main.c">'single_main.c'</a> thatwe want to compile. We will do so using a command line similar to this:<br><br><code>cc single_main.c</code><br><br>Note that we assume the compiler is called "cc". If you're using a GNU compiler,you'll write 'gcc' instead. If you're using a Solaris system, you might use'acc', and so on. Every compiler might show its messages (errors, warnings,etc.) differently, but in all cases, you'll get a file 'a.out' as a result,if the compilation completed successfully. Note that some older systems(e.g. SunOs) come with a C compiler that does not understand ANSI-C, but ratherthe older 'K&R' C style. In such a case, you'll need to use gcc (hopefullyit is installed), or learn the differences between ANSI-C and K&R C (notrecommended if you don't <em>really</em> have to), or move to a differentsystem.</p><p>You might complain that 'a.out' is a too generic name (where does it come fromanyway? - well, that's a historical name, due to the usage of something called "a.out format" for programs compiled on older Unix systems). Supposethat you want the resulting program to be called "single_main". In that case,you could use the following line to compile it:<br><br><code>cc single_main.c -o single_main</code><br><br>Every compiler I've met so far (including the glorious gcc) recognized the '-o'flag as "name the resulting executable file 'single_main'".</p><hr size=4><a name="running_the_exe"><font color=brown><h2>Running The Resulting Program</h2></font></a><p>Once we created the program, we wish to run it. This is usually done by simplytyping its name, as in:<br><br><code>single_main</code><br><br>However, this requires that the current directory be in our PATH (which isa variable telling our Unix shell where to look for programs we're tryingto run). In many cases, this directory is not placed in our PATH. Aha! - we say.Then lets show this computer who is smarter, and thus we try:<br><br><code>./single_main</code><br><br>This time we explicitly told our Unix shell that we want to run the programfrom the current directory. If we're lucky enough, this will suffice. However,yet one more obstacle could block our path - file permission flags.</p><p>When a file is created in the system, it is immediately given some accesspermission flags. These flags tell the system who should be given accessto the file, and what kind of access will be given to them. TraditionalUnix systems use 3 kinds of entities to which they grant (or deny) access:The user which owns the file, the group which owns the file, andeverybody else. Each of these entities may be given access to read the file('r'), write to the file ('w') and execute the file ('x').</p><p>Now, when the compiler created the program file for us, we became owners ofthe file. Normally, the compiler would make sure that we get all permissionsto the file - read, write and execute. It might be, thought that somethingwent wrong, and the permissions are set differently. In that case, we canset the permissions of the file properly (the owner of a file can normallychange the permission flags of the file), using a command like this:<br><br><code>chmod u+rwx single_main</code><br><br>This means "the user ('u') should be given ('+') permissions read ('r'),write ('w') and execute ('x') to the file 'single_main'. Now we'll surely beable to run our program. Again, normally you'll have no problem running thefile, but if you copy it to a different directory, or transfer it to adifferent computer over the network, it might loose its original permissions,and thus you'll need to set them properly, as shown above. Note too that youcannot just move the file to a different computer an expect it to run - it hasto be a computer with a matching operating system (to understand the executablefile format), and matching CPU architecture (to understand the machine-languagecode that the executable file contains).</p><p>Finally, the run-time environmenthas to match. For example, if we compiled the program on an operating systemwith one version of the standard C library, and we try to run it on a versionwith an incompatible standard C library, the program might crush, or complainthat it cannot find the relevant C library. This is especially true for systemsthat evolve quickly (e.g. Linux with libc5 vs. Linux with libc6), so beware.</p><hr size=4><a name="debug_info"><font color=brown><h2>Creating Debug-Ready Code</h2></font></a></a><p>Normally, when we write a program, we want to be able to debug it - that is,test it using a debugger that allows running it step by step, settinga break point before a given command is executed, looking at contentsof variables during program execution, and so on. In order for the debuggerto be able to relate between the executable program and the original sourcecode, we need to tell the compiler to insert information to the resultingexecutable program that'll help the debugger. This information is called"debug information". In order to add that to our program, lets compile itdifferently:<br><br><code>cc -g single_main.c -o single_main</code><br><br>The '-g' flag tells the compiler to use debug info, and is recognized bymostly any compiler out there. You will note that the resulting file is muchlarger than that created without usage of the '-g' flag. The difference in sizeis due to the debug information. We may still remove this debug informationusing the <code>strip</code> command, like this:<br><br><code>strip single_main</code><br><br>You'll note that the size of the file now is even smaller than if we didn't usethe '-g' flag in the first place. This is because even a program compiledwithout the '-g' flag contains some symbol information (function names,for instance), that the <code>strip</code> command removes. You may want toread <code>strip</code>'s manual page (man strip) to understand moreabout what this command does.</p><hr size=4><a name="optimize"><font color=brown><h2>Creating Optimized Code</h2></font></a><p>After we created a program and debugged it properly, we normally want itto compile into an efficient code, and the resulting file to be as smallas possible. The compiler can help us by optimizing the code, eitherfor speed (to run faster), or for space (to occupy a smaller space), orsome combination of the two. The basic way to create an optimizedprogram would be like this:<br><br><code>cc -O single_main.c -o single_main</code><br><br>The '-O' flag tells the compiler to optimize the code. This also meansthe compilation will take longer, as the compiler tries to applyvarious optimization algorithms to the code. This optimization is supposedto be conservative, in that it ensures us the code will still perform thesame functionality as it did when compiled without optimization (well,unless there are bugs in our compiler). Usually can define an optimizationlevel by adding a number to the '-O' flag. The higher the number - thebetter optimized the resulting program will be, and the slower the compilerwill complete the compilation. One should note that because optimizationalters the code in various ways, as we increase the optimization levelof the code, the chances are higher that an improper optimization willactually alter our code, as some of them tend to be non-conservative,or are simply rather complex, and contain bugs. For example, for a long time it was known that using a compilation level higher than 2 (or wasit higher than 3?) with gcc results bugs in the executable program. Afterbeing warned, if we still want to use a different optimization level (letssay 4), we can do it this way:<br><br><code>cc -O4 single_compile.c -o single_compile</code><br><br>And we're done with it. If you'll read your compiler's manual page, you'llsoon notice that it supports an almost infinite number of command line optionsdealing with optimization. Using them properly requires thorough understandingof compilation theory and source code optimization theory, or you might damageyour resulting code. A good compilation theory course (preferably based on"the Dragon Book" by Aho, Sethi and Ulman) could do you good.</p>
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -