My C programming experience is pretty limited, and recently I was trying to convert a monolithic program into separate files/modules. Here are a few notes on the process, in particular the various C language storage classes.
- Each source file (e.g.
mymodule.c) will be compiled to an object file (e.g.mymodule.o) - The object files are then linked together to form an executable file or image (i.e. the program file).
staticglobal variables are visible to all functions within the current source file. They are not accessible to functions defined in other files.- Global variables are
staticunless declared otherwise. staticlocal variables (i.e.staticvariables declared within a function) are initialised at run-time but not re-initialised when the function is called.externglobal variables are visible to all modules, not just functions within the current source file. Use these for variables to be shared among modules/files.externvariables cannot be initialised in the file declaring them asextern. However, other modules sharing them can initialise them, as they are notexternin that context.- If sharing a module among others, write its function prototypes in a header (
.h) file, and the function definitions in a source (.c) file. Then just#includethe.hfile in any dependent modules (do not include the.cfile, as this will double up on definitions!).
Typical compilation and linking routine to create an executable:
$ gcc -c -o mymodule.o mymodule.c $ gcc -c -o anothermodule.o anothermodule.c $ gcc -c -o main.o main.c # Linking stage; note use of gcc, not ld! $ gcc -o myprogram main.o mymodule.o anothermodule.o