4. C/C++ compilation

4.1. Gcc

4.1.1. Gcc getting started

C program
// hello.c
#include <stdio.h>
void main(void)
{
    printf ("hello world!\n");
}

// compile the source file hello.c. Generate the output file a.out
gcc hello.c

// give the output file a name
gcc hello.c -o hello
chmod a+x hello
./hello
C++ program
// hello.cpp
#include <iostream>
using namespace std;

int main() {
cout << "Hello, world!" << endl;
return 0;
}

g++ -o hello hello.cpp
chmod a+x hello
./hello

4.1.2. Gcc compilation process

4.1.3. Various examples

Some compiler options
-o: specifies the output executable filename.
-Wall: prints "all" Warning messages.
-g: generates additional symbolic debuggging information for use with gdb debugger.
-v: verbose mode
-S: compile into assenbly
-D: macro definition. -Dname=value
Examples
gcc -Wall -g -o hello hello.c

gcc -v -o hello hello.c

// compile a program with 2 source files
g++ -o myprog file1.cpp file2.cpp
// or
g++ -c file1.cpp
g++ -c file2.cpp
g++ -o myprog file1.o file2.o
Cross compilation for ARM Cortex-M
arm-none-eabi-gcc -c test.c -mthumb -mcpu=cortex-m4

arm-none-eabi-ld -o image.elf object1.o object2.o -T linker_script.ld -Map=map_file.map

4.1.4. Analyse the compiled file

4.1.5. Libraries

4.1.5.1. Headers .h

4.1.5.2. Static Library .lib .a

4.1.5.3. Shared Library .dll .so

4.1.6. pkg-config

gcc -o test test.c pkg-config –libs –cflags glib-2.0

pkg-config –libs –cflags glib-2.0

4.1.7. Environment Variables

4.2. Debugging

4.2.1. Gdb

4.3. Gcc MCU

ARM Cortex-M section in MCU