eBook: Integration and Automation of Manufacturing Systems
   



TOC PREV NEXT

3.6 COMPILING C PROGRAMS IN LINUX


The basic C compiler is called 'gcc', or 'g++' for C++. These can be put on a command line. For example 'gcc bob.c -o bob' will compile a C program in the file 'bob.c', and store the result in a program file 'bob'.

Function libraries linked in with '-l___'. For example to use a math function the math library must be included in the compilation line with '-lm'. The debugger can be used if '-g' is included in the compilation line. For example, if a program was compiled with 'gcc -g bob.c -o bob', it could be run in the debugger with 'xxgdb bob'. This then allows you to step through the program line by line, set break points, see where it crashed, or print data values. The compiler can be set to be extra picky (which also helps find errors) when compiled with the flag '-Wall'

3.6.1 Makefiles

Programmers quickly tire of constantly typing commands to compile programs. To help with this problem, the make utility was developed. A programmer will create a 'makefile' to describe how a program is to be compiled. This file can be called 'makefile' or 'Makefile' by default. The contents then describe when a file should be compiled.

The sample makefile below shows a simple makefile. The lines beginning with '#' are comments. The line containing the 'all:' indicates the main program(s) to make. In this example the only program to make is 'bob', notice that a later line starts with 'bob:'. The next three lines define variables that can be reused. Later in this example the '$(CC)' will be replaced with 'gcc', the '$(CFLAGS)' with '-Wall -g', and so on. To make the required program 'bob' both 'bob.c' and 'bill.o' are needed. When run the make tool will check to see if the files on the disk have been updated and things need to be recompiled. Only if the program files have changed will the compiler be run, otherwise the compilation will not be done because it is not necessary. If it is necessary it will execute the commands on the following lines.



Figure 3.15 - A Sample Makefile

Initially creating a makefile seems to be alot of effort, but if you run the compiler 10 times you will save enough time to make it worth while. It also makes it easier for others to compile the programs later.

TOC PREV NEXT

Search for More:

Custom Search