C Fundamentals

Program Structure, Types and Operators

The building blocks of C programs: preprocessors, data types, and operators. Since BPF programs are written in C, these fundamentals are critical.

1.1 Program Structure and Preprocessors

  • #include - including header files
  • #define - defining macros
  • #ifndef / #endif - header guards (prevents double inclusion)
  • #pragma directives - special instructions for the compiler
  • Macro functions - compile-time code generation

Used in BPF:

  • SEC() macro -> __attribute__((section(NAME), used))
  • #include "ep_platform.h" - eBPFHub platform header
  • #pragma unroll - bounded loop optimization
#define SEC(NAME) __attribute__((section(NAME), used))

SEC("xdp")
int xdp_prog(struct xdp_md *ctx) { ... }
// -> places into the .xdp section, prevents the linker from discarding it

eBPFHub: In the Chapter 0 -> “Platform overview” exercise, you will see the SEC() macro, #include usage, and your first BPF program structure.

See in xdp-tutorial: basic01-xdp-pass/xdp_pass_kern.c - see how the SEC() macro is defined.

Exercise: Write your own header file, add a header guard, and define a macro.


1.2 Data Types and Format Specifiers

  • int, char, short, long, unsigned types
  • sizeof operator
  • Type casting
  • Format specifiers: %d, %u, %x, %s, %p, %llu

Types used in BPF: __u8, __u16, __u32, __u64, __s32, __be16

Format specifiers are critical for bpf_printk:

  • %d -> int
  • %u -> unsigned int
  • %x -> hex
  • %llu -> __u64
  • %s -> string (limited)

eBPFHub: In the “Process context” exercise, you will see char[16] buffer usage with bpf_get_current_comm(&buf, sizeof(buf)).

See in xdp-tutorial: common/xdp_stats_kern_user.h - struct datarec definition.

Exercise: Print the sizes of different types using sizeof, and format them with printf.


1.3 Operators and Bitwise Operations

  • Arithmetic: +, -, *, /, %
  • Bitwise: &, |, ^, ~, <<, >>
  • Comparison: ==, !=, <, >, <=, >=
  • Logical: &&, ||, !

Critical in BPF: Bit masking (extracting VLAN IDs, flag checks)

eBPFHub: In the “Reading event data” exercise, you will practice bitwise operations with __data_loc field decoding: lower 16 bits = offset, upper 16 bits = length.

offset = loc & 0xFFFF;
len = loc >> 16;

Exercise:

  1. Set/clear a specific bit of a number
  2. Split an IP address into 4 octets (using >> and &)