C anatomy
main.c
By convention, main.c is the target to be compiled into an executable. When built/run, the contents of the function
int main()
is the code that actually runs.
/* * Multiline comment */ #include <stdio.h> int main( int argc, char *argv[] ) { printf( "Number of CLI arguments: %d", argc ); printf( "Script Name: %s", argv[0] ); // comment int num = 6; puts( "Hello World"); printf("My Number is: %d", num); return 0; }
library
Every .c file intended for include should implement a header file.
Header files determine what functions become available when a module is imported.
C/C++ do not have a module system like python. Wherever an include is performed, that sourcefile's code is inserted into your module during compilation. If multiple functions/variables are imported with the same name, that causes your build to fail.
In order to prevent this, your header files must have import guards (ifndef, define, endif). They check the current state of the compiler to see if the file has already been included, ignoring the request if so.
By convention, the variable defined by ifndef is your modulename in allcaps, followed by
_H
.// libhelloworld.h ifndef LIBHELLOWORLD_H define LIBHELLOWORLD_H void helloworld(); endif// libhelloworld.c #include <stdlib.h> void helloworld() { printf("hello world"); }// main.c #include "libhelloworld.h" int main(int argc, char *argv[]){ print_helloworld(); exit 0; }Note the different styles of include:
#include <stdlib.h> // external imports are wrapped in '<' and '>' #include libhelloworld.h // internal imports (relative to your sourcefile) are wrapped in '"'s