Linux notes

C Fundamentals

Compiling a single C/C++ source file

gcc -Wall {inputfilename} -o {outputfilename}
For example, to compile the following C program:
/* File: hello.c */

#include <stdio.h>

int main (void)
{
	printf("Hello, world!\n");
	return 0;
}
we would use the following gcc command:
gcc -Wall hello.c -o hello
This compiles the C source code in the file hello.c and produces the executable file hello. For C++, the syntax is very similar, except that gcc is replaced by g++:
g++ -Wall {inputfilename} -o {outputfilename}
For example,
g++ -Wall hello.cpp -o hello

Compiling multiple C/C++ source files

Multiple C or C++ source files may be compiled and linked into a single executable output file, by listing them in the arguments to gcc or g++. For example, a program may consist of the following files:
/* File: main.c */

#include "hello.h"

int main (void)
{
	hello ("world");
	return 0;
}
/* File: hello.h */

void hello (const char * name);
/* File: hello_fn.c */

#include <stdio.h>
#include "hello.h"

void hello (const char * name)
{
	printf("Hello, %s!\n", name);
}
The following command gathers all the files into the compilation and linking process and produces a single executable output file, hello. Note that the header file (hello.h) is not listed in the files passed as arguments to gcc/g++. This is because the other two source files (main.c and hello_fn.c) already include references to it.
gcc -Wall main.c hello_fn.c -o hello
The output file (hello) produces exactly the same result as the 'single source file' case.