C cheatsheet

compile/assemble/link

ldd  # print shared library dependencies

ldd pdo.so

    linux-vdso.so.1 =>  (0x00007fffda9fe000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f1557cf5000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f15582f4000)

static and dynamic library

three files:

hello.cpp:

#include <iostream>  

using namespace std;  

void hello(void) {   
    cout <<"Hello "<<endl;  
}

hello.h:

void hello(void);

main.cpp:

#include "hello.h"  

int main(int argc,char *argv[]) {   
    hello();  
    return 0;  
}

compile static library

$ ls
hello.cpp  hello.h  main.cpp

$ gcc -o hello.o -c hello.cpp
$ ls
hello.cpp  hello.h  hello.o  main.cpp

# create static library
$ ar cqs libHello.a hello.o 
$ ls
hello.cpp  hello.h  hello.o  libHello.a  main.cpp

# link against static library
$ g++ -o out_static main.cpp -L./ -lHello
$ ls
hello.cpp  hello.h  hello.o  libHello.a  main.cpp  out_static
$ ./out_static 
Hello

compile dynamic library

# create dynamic library
$ g++ -O -fpic -shared -o libHello.so hello.cpp
$ ls
hello.cpp  hello.h  hello.o  libHello.a  libHello.so  main.cpp  out_static

# link against dynamic library (this command is the same as when build static executable, libHello.so is preferred over libHello.a)
$ g++ -o out_dynamic main.cpp -L./ -lHello
$ ls
hello.cpp  hello.o     libHello.so  out_dynamic
hello.h    libHello.a  main.cpp     out_static

$ ./out_dynamic 
Hello

library dependency comparison:

$ ldd out_static 
    linux-vdso.so.1 =>  (0x00007fff46304000)
    libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f2d2de19000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f2d2da50000)
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f2d2d74a000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f2d2e136000)
    libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f2d2d534000)

$ ldd out_dynamic 
    linux-vdso.so.1 =>  (0x00007fff533fe000)
    libHello.so => ./libHello.so (0x00007f786bd8c000) # depends on libHello.so
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f786b9ab000)
    libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f786b6a7000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f786bf90000)
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f786b3a2000)
    libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f786b18c000)

update dynamic library:

# replace 'Hello' with 'Dog' in hello.cpp
$ vi hello.cpp

# rebuild .so file
$ g++ -O -fpic -shared -o libHello.so hello.cpp

# updated
$ ./out_dynamic 
Dog

# not changed
$ ./out_static 
Hello