Code: PRINCIPLE OF SEPARATED COMPILING When you develop large program usually source code is separated to some files. These files compile separately and linked into one program. Here we describe method of separated compiling and note general points that must be important during sourcecode writing. 1. Notes to sourcecode There are two serious problems of separated compiling of large programs: - links to functions from other files; - ability to get common data.
Below we try to solve that problems with examples. See this program: #include <stdio.h> int a[10]; char b[4]; char main() { char sub1(),sub2(); sub1(); sub2(); printf("%d,%d,%d\n",a[0],a[3],a[9]); printf("%c,%c,%c\n",b[0],b[1],b[2]); } char sub1() { a[0]=1; a[3]=2; a[9]=3; } char sub2() { b[0]='a'; b[1]='b'; b[2]='c'; } Text of the program is divided on three files namely PROG1, PROG2 and PROG3 that consist of main function and functions 1 and 2: PROG1.C: #include <stdio.h> int a[10]; char b[4]; char main() { : : } PROG2.C: extern int a[10]; char sub1() { : : } PROG3.C: extern char b[4]; char sub2() { : : } Function "main" calls functions "sub1" and "sub2" and we need use definition of that functions. Functions "sub1" and "sub2" call nothing and do not need in any function definitions. Using arrais "a" and "b" is a problem too. Identifier "a" used in "main" and "sub1". Identifier "b" used in "main" and "sub2". For all of that files must be linked.
To link identifiers word "extern" is used. In first file PROG1.C this word is not needed, but in other two files it is. It reflects that arrays "a" and "b" defined in file PROG1.C, but in other files these arrays are absent. If a number of files will use definitions without word "extern" error of name duplicating appears. In other hand we can't use "extern" in all definitions because it may be undefined object. Therefore we must be use the only definition without "extern". All other definitions of the same identifier must be "extern". 2. Compile and link Described above sourcecode must be compiled and linked by the sequence of actions: cc1 prog1 cc1 prog2 cc1 prog3 cc2 prog1 cc2 prog2 cc2 prog3 as prog1 as prog2 as prog3 ld prog=prog1,prog2,prog3,clib/l/gXMAIN If all parts (all files) are compiled already and we need recompile the only file (for example PROG2.C) another sequence must be used: cc1 prog2 cc2 prog2 as prog2 ld prog=prog1,prog2,prog3,clib/l/gXMAIN
|