18th March 2012

c Reference

Basic Types

unsigned int         %u        2U
unsigned long        %lu       2UL
unsigned long long   %llu      2ULL

unsigned int         %x        2U
unsigned long        %lx       2UL
unsigned long long   %llx      2ULL

long long            %j        2LL

size_t               %zu %z    sizeof()
ssize_t              %zd

void*                %p
ptrdiff_t            %tx       pa - pb

char                 %c        'a'
wchar_t              %lc       L'a'
char[]               %s        "a"
wchar_t[]            %ls       L"a"

GCC Flags

For C99:

-std=c99

For bug-finding:

-Wall -Wconversion -pedantic -Werror

For security:

-D_FORTIFY_SOURCE=2

For extra lint checks and UNUSED argument declaration:

-Wextra -DUNUSED=__attribute__((unused))

MacOS X compat level:

-mmacosx-version-min=10.5

Shared Libraries

Compile flags: position independent code, limit visibility:

-shared -fPIC -fvisibility=hidden

Make API/ABI symbols explicitly visible:

__attribute__((visibility("default")))
void
foo(void)
{
    /* ... */
}

Library init/fini:

__attribute__((constructor))
void
init(void)
{
    /* ... */
}

__attribute__((destructor))
void
fini(void)
{
    /* ... */
}

GDB

Backtrace:

bt
bt full

Threading:

info threads
thread 3

Cookbook

Quick and dirty LD_PRELOAD hooking:

#include <sys/types.h>
#include <dlfcn.h>

/*
 * gcc -shared -fPIC -o libhook.so hook.c [-ldl]
 * LD_PRELOAD=./libhook.so ./hooked
 */

int
foobar(int arg0, int arg1, ...)
{
        int (*oldfoobar)(int, int, ...);

        oldfoobar = dlsym(RTLD_NEXT, "foobar");

        /* modify or log arg0, arg1, ... */

        return oldfoobar(arg0, arg1, ...);
}

Back to Knowledge Base.