Annotation of wikisrc/examples/basic_unix_programming.mdwn, revision 1.1

1.1     ! mspo        1: **Contents**
        !             2: 
        !             3: [[!toc ]]
        !             4: 
        !             5: ## Introduction
        !             6: 
        !             7: This is a guide to Unix programming. It is intended to be as generic as possible, since we want to create programs that are as portable as NetBSD itself.
        !             8: 
        !             9: ## Compiling a C program
        !            10: 
        !            11: I will assume you know C and how to edit a file under Unix.
        !            12: 
        !            13: First, type in the code to your file, let's say we put it in 'hello.c'. Now, to create a program from it, do the following:
        !            14: 
        !            15:     $ gcc hello.c -o hello
        !            16:     <compiler output>
        !            17: 
        !            18: If gcc (GNU Compiler Collection) is not available, use the command 'cc' instead of 'gcc'. Command line switches can be different, though. If you use C++, everything said here is the same, but you may replace the 'gcc' by 'g++'.
        !            19: 
        !            20: Now if there were no compiler errors, you can find the file 'hello' in the current working directory. To execute this program, type
        !            21: 
        !            22:     $ ./hello
        !            23:     <Your program's output>
        !            24: 
        !            25: The reason you can't just type 'hello' is a good one but I won't explain it here. **Beware, with some shells, the current line is overwritten when the program quits**, so be sure to include at least a newline (\n) in the last line you print to the screen. This can be very frustrating if the program seems to give no output.
        !            26: 
        !            27: To compile larger programs, you can do this:
        !            28: 
        !            29:     $ gcc -c file1.c
        !            30:     <compiler output>
        !            31: 
        !            32: And the same for file2.c etc. The -c switch tells gcc to only compile the code, and not link it into a complete program. This will result in a file with the same name as the source file, except the '.c' is replaced by '.o'.
        !            33: 
        !            34: Now, once you have compiled all your .c modules, you can tie the resulting object files (those with a .o extension) together with the following:
        !            35: 
        !            36:     $ gcc file1.o file2.o file3.o -o program
        !            37:     <linker output>
        !            38: 
        !            39: Gcc now will link the object files together into your program. If all went good, you can run the program again with './program'.
        !            40: 
        !            41: If you forget the -o switch on linking, the resulting default program will be called 'a.out' and will be placed in the current working directory.
        !            42: 
        !            43: If an include file can't be found, you can use the -I switch to point gcc to the correct path. Example:
        !            44: 
        !            45:     $ gcc -c -I/usr/local/include blah.c
        !            46: 
        !            47: This will compile blah.c into blah.o, and when it comes across a #include, it will look in /usr/local/include for that file if it can't find it in the default system include directory (or the current directory).
        !            48: 
        !            49: When you start using libraries (like libX11), you can use the -l, -L and -R flags when linking. This works as follows:
        !            50: 
        !            51:     $ gcc -lX11 blah.o -o program
        !            52: 
        !            53: This will try to link the program to the file '', or 'libX11.a' depending on if your system is dynamically or statically linked.
        !            54: 
        !            55: Usually, the linker can't find libraries, so always use the following command:
        !            56: 
        !            57:     $ gcc -L/usr/X11R6 -R/usr/X11R6 -lX11 blah.o -o program
        !            58: 
        !            59: The -L flag tells the linker where to find the '' or 'libX11.a' file. The -R flag is for 'tying in' this path into the program. The reason this needs to be done next to the -L, is that when the system is dynamically linked, the library will be accessed on demand. On statically linked systems, the 'libX11.a' file's contents will be copied into the final binary, which will make it a lot bigger. Nowadays, almost all systems are dynamically linked, so the '' file is used. But the contents are not copied over. The library itself will be accessed whenever the program is started.
        !            60: 
        !            61: To make sure the dynamical linker can find the library, you need to tie in the library's path. Some systems (notably, most Linuxen) function even when you don't tie in the path yourself, because it 'knows' about some common paths, but some other, more correct systems do not 'know' any of the common paths. This seems to be for security reasons, but I don't know the exact details of why this is insecure (probably has to do with chrooted environments). It never hurts to use '-R', so please do so in every project you do, since you might some day want to run it on another system.
        !            62: 
        !            63: ## Using Make
        !            64: 
        !            65: It can be tedious work to type in those long command lines all the time, so you probably want to use Make to automate this task.
        !            66: 
        !            67: A Makefile generally looks like the following:
        !            68: 
        !            69:     # This is a comment
        !            70:     program: hello.o
        !            71:        gcc hello.o -o program
        !            72: 
        !            73:     hello.o: hello.c
        !            74:        gcc -c hello.c
        !            75: 
        !            76: Just save the things between the lines as the file called 'Makefile' and type 'make'. Make will try to build the first 'target' (a word followed by a colon) it encounters, which is in our case 'program'. It looks at what is required before it can do so, which is hello.o (after the colon). **Warning: The whitespace in front of the commands below the target must be exactly one tab, or it will not work**. This is a deeply propagated bug in all versions of Make. (don't let anyone convince you it's a feature. It's not)
        !            77: 
        !            78: So if 'hello.o' does not exist, before Make can build 'program', it must first build 'hello.o'. This can be done from 'hello.c', as it can see in the next target. If hello.o already existed, it will look if hello.c is newer (in date/time) than hello.o. If this is not the case, it will not have to rebuild hello.o, as obviously(?) the file hasn't been modified. If the file is newer, it will have to rebuild hello.o from hello.c.
        !            79: 
        !            80: When Make has determined that it must build a target, it will look at the indented lines (with a tab) directly following the target line. These are the command it will execute in sequence, expecting the target file to be a result of executing these commands.
        !            81: 
        !            82: If you wish to build a particular file only, just type 'make <target>', where target is the name of the target you wish to build. Now we'll conclude with a bigger example of a Makefile:
        !            83: 
        !            84:     # Assign variables.  Doing this makes the Makefile easier to
        !            85:     # modify if a path is incorrect, or another compiler is used.
        !            86:     LINKFLAGS=-L/usr/X11R6/lib -R/usr/X11R6/lib
        !            87:     
        !            88:     # NB! Don't assign CC, like many linux folks do it makes impossible 
        !            89:     # to use another compiler without changing the source
        !            90:     
        !            91:     # If an 'all' target is present, it is always executed by default
        !            92:     # (when you just type 'make') even if it's not the first target.
        !            93:     all: myprog
        !            94:     
        !            95:     # In the following, '${CC}' will expand to the contents of the
        !            96:     # variable 'CC'.
        !            97:     myprog: first.o second.o
        !            98:        ${CC} ${LINKFLAGS} -lX11 first.o second.o  -o myprog
        !            99:     
        !           100:     first.o: first.c
        !           101:        ${CC} -c first.c
        !           102:     
        !           103:     second.o: second.c
        !           104:        ${CC} -c second.c
        !           105:     
        !           106: As you can see, you can do rather interesting things with Make.
        !           107: 
        !           108: Consider using BSD Make scripts, they simplify handling projects a lot. System builds using them.
        !           109: 
        !           110: ## Using BSD Make
        !           111: 
        !           112: Makefiles are nice, but typing the same lines all the time can get very annoying, even if you use SUFFIXES.
        !           113: 
        !           114: BSD's Make is a very nice Make, which comes pre-packed with some files which can make your life a lot easier and your Makefiles more elegant, but it is **not compatible with GNU make**. Some things are even incompatible between the Makes of different versions of BSD. Now we got that out of the way, let's see an example:
        !           115: 
        !           116:     PROG=   test
        !           117:     SRCS=   test_a.c test_b.c
        !           118:     # We have written no manpage yet, so tell Make not to try and
        !           119:     # build it from nroff sources.  If you do have a manpage, you
        !           120:     #  usually won't need this line since the default name
        !           121:     #  of the manpage is ${PROG}.1 .
        !           122:     MAN=
        !           123:     
        !           124:     .include <>
        !           125: 
        !           126: That's all there's to it! Put this in the same directory as the 'test' program's sources and you're good to go.
        !           127: 
        !           128: If you're on a non-BSD system, chances are that the normal 'make' program will choke on this file. In that case, the BSD Make might be installed as 'pmake', or 'bmake'. On Mac OS X, BSD make is called 'bsdmake', the default 'make' is GNU Make. If you can't find make on your particular system, ask your administrator about it.
        !           129: 
        !           130: The file (in /usr/share/mk) does all the work of building the program, taking care of dependencies etc. This file also makes available a plethora of targets, like 'all', 'clean', 'distclean' and even 'install'. A good BSD Make implementation will even call 'lint' on your source files to ensure your code is nice and clean.
        !           131: 
        !           132: If you wish to add flags to the C compiler, the clean way to do it is like this:
        !           133: 
        !           134:     CFLAGS+= -I/usr/X11R6/include
        !           135: 
        !           136: For the linker, this is done by
        !           137: 
        !           138:     LDADD=     -lX11
        !           139: 
        !           140: If you're adding libraries or include paths, be sure to make lint know about them:
        !           141: 
        !           142:     LINTFLAGS+=        -lX11 -I/usr/X11R6/include
        !           143: 
        !           144: If you're creating a library, the Makefile looks slightly different:
        !           145: 
        !           146:     LIB=    mylib
        !           147:     SRCS=   mylib_a.c mylib_b.c
        !           148:     
        !           149:     .include <>
        !           150: 
        !           151: A library doesn't have a manpage by default. You can force one to be built by supplying a MAN line, of course.
        !           152: 
        !           153: As you can see, the BSD Make system is extremely elegant for large projects. For simple projects also, but only if you have one program per directory. The system does not handle multiple programs in one directory at all. Of course, in large projects, using directories for each program is a must to keep the project structured, so this shouldn't be a major problem.
        !           154: 
        !           155: The main directory of a project should contain this Makefile:
        !           156: 
        !           157:     SUBDIR=         test mylib
        !           158:     
        !           159:     .include <>
        !           160: 
        !           161: Additionally, and always include the file ../, so you can keep global settings (like DEBUG switches etc) in a file at toplevel.
        !           162: 
        !           163: For more information, usually there is a /usr/share/mk/bsd.README file which explains BSD Make more completely than this little document. See also [[BSD Make]].
        !           164: 
        !           165: **Tip**: Use [LaTeX-mk]( if you want to build LaTeX sources with this type of BSD Makefiles.
        !           166: 
        !           167: ## Debugging programs with gdb
        !           168: 
        !           169: Now you know how to compile and link a program, but debugging is often very useful as well. I'll quickly explain some common things one can do with gdb, the GNU debugger.
        !           170: 
        !           171: At first, when you see someone using the debugger, it looks like yet another black art that can be done by gurus only, but it's not really too difficult, especially considering it's a command line debugger. If you practice a bit, using gdb will become a second nature.
        !           172: 
        !           173: First, it is handy to compile a program with debugging symbols. This means the debugger knows about the variable and function names you use in your program. To do this, use the -g switch for gcc when compiling:
        !           174: 
        !           175:     $ gcc -g blah.c -o program
        !           176: 
        !           177: For each object, you must use -g on compilation. On linking -g can beomitted. Now, run the debugger:
        !           178: 
        !           179:     $ gdb program
        !           180:     <output and prompt>
        !           181: 
        !           182: To run the program, just type 'run'. To load a new binary into gdb, use "file <binary>". For information about possible commands, use 'help'.
        !           183: 
        !           184: When your program crashes, you can use the command 'bt' to examine the stack. With 'select <N>' you can select stack frame N. For example, suppose you're in the middle of a function foo which is called from function bar, you can switch to bar by going down a step in the stack. Stack frame 0 is always the last called function.
        !           185: 
        !           186: With 'l' (or 'list') you can list a certain file, at a certain point. By default 'l' shows the point where the debugger has halted right now. It always lists 10 lines of context, with the middle line being the current line. If you wish to see some other file or some other line, use 'l file.c:line', with file.c being the file to look at, line the number of the line. With every consecutive 'l', the next lines will be shown, so you can scroll through the program by hitting 'l' all the time.
        !           187: 
        !           188: The nice thing about gdb is, that when you simply press enter, it executes the last command. So you need to type 'l' only once, and keep pressing enter until you see the right piece of code. This is especially useful when using 'step' (see below).
        !           189: 
        !           190: To investigate a variable, just use 'print <varname>'. You can print contents of pointers in the same fashion as you would in C itself, by prefixing it with a *. You can also cast to int, char etc if you wish to see only that many bits of the memory (useful when investigating buffers). Printing a variable only works if you've selected a stack frame in which the variable has a meaning. So if function foo has an integer called 'i' and function bar also has one, it depends on the selected stack frame which of the two i's contents you get to see.
        !           191: 
        !           192: With 'break' you can set breakpoints. The program being debugged will stop when it gets to the line of the breakpoint. Breakpoints work like listings when giving line numbers/filenames. You can clear a breakpoint by issuing the same, but with 'break' replaced by 'clear'.
        !           193: 
        !           194: To continue the program, use 'continue'. This just resumes executing the program from the point where it halted. If the program really crashed, continue is of course not possible.
        !           195: 
        !           196: To walk through a program line by line, use 'step'. This way, after each line is executed, you can investigate how variables changed. It is common practice to set a breakpoint at a place in the program where you expect a problem to occur. When that breakpoint is hit, you can use 'step' to step through the failing part of the program.
        !           197: 
        !           198: If you think a certain function will work, use 'finish', which is like a continue, but only for the current function. When the previous function is recalled from the stack, the program will stop.
        !           199: 
        !           200: With 'kill' you can immediately kill your program. 'quit' quits gdb.
        !           201: 
        !           202: ## References
        !           203: 
        !           204: * [[BSD Make]]
        !           205: * [LaTeX-mk](

CVSweb for NetBSD wikisrc <> software: FreeBSD-CVSweb