2007-09-30

C basics: using separate files/modules

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).
  • static global variables are visible to all functions within the current source file. They are not accessible to functions defined in other files.
  • Global variables are static unless declared otherwise.
  • static local variables (i.e. static variables declared within a function) are initialised at run-time but not re-initialised when the function is called.
  • extern global variables are visible to all modules, not just functions within the current source file. Use these for variables to be shared among modules/files.
  • extern variables cannot be initialised in the file declaring them as extern. However, other modules sharing them can initialise them, as they are not extern in 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 #include the .h file in any dependent modules (do not include the .c file, 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

No comments: