C Compiling

Code Generation

-march=native generates code optimized for the local machine with all the supported instruction subsets. But only for running in the local machine or equivalent. Other archs for x86: i386, i686, pentium4, athlon, k8, etc.

To see what -march=native does, run:

gcc -march=native -E -v - </dev/null 2>&1 | grep cc1

or

gcc -Q --help=target -march=native

-m32 generates 32 bits code on a 64 bits toolchain.

Basic compilation

All-in-one

gcc main.c mylib.c -o program

Compiling and then linking

gcc -c main.c mylib.c
gcc main.o lib.o -o program

Static Linking

gcc -static main.c mylib.c -o program

Creating Libraries

Dynamic library

Create

gcc -c -fpic mylib.c
gcc -shared mylib.o -o libmylib.so'

or

gcc -fpic -shared mylib.c -o libmylib.so

Linking

gcc main.c -L. -lmylib -o program

or

gcc main.c mylib.so -o program

Running

LD_LIBRARY_PATH=. ./program

The -L and LD_LIBRARY_PATH are needed when the library isn't in the library path. When the library is in the same directory, it can be used like any other object file.

Static Library

Create

gcc -c mylib.c
ar rcs libmylib.a mylib.o

Linking

gcc main.c -L. -lmylib -o program

or

gcc main.c mylib.a -o program

Running

./program

Make

To compile a single file like source.c without a Makefile:

make source

To run multiple compilations simultaneously:

make -j3 # The ideal number is the number of CPUs

Simple Makefile

program: file1.o file2.o
	gcc -O2 file1.o file2.o -o program

file1.o: file1.c
	gcc -O2 -c file1.c

file2.o: file2.c
	gcc -O2 -c file2.c

clean:
	rm -f *.o program

Generic Makefile

PROG = program
CFLAGS = -O2
SRC = $(wildcard *.c)
OBJ = $(SRC:%.c=%.o)

$(PROG): $(OBJ)
	$(CC) $(OBJ) -o $(PROG)

%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

clean:
	$(RM) $(OBJ) $(PROG)