Place Code and Data in Custom Sections With the section Attribute
Use __attribute__((section)) to put functions and variables in named ELF sections, then walk the section with the linker's start and stop symbols.

By default GCC chooses the section of every function and variable: code goes to .text, initialized data to .data, zero-initialized data to .bss, constants to .rodata. The section attribute overrides that choice for one object, and the override unlocks two uses that are hard to get any other way. One is placement: put a function in a RAM-resident section, put a buffer in a memory region the linker script reserves for DMA. The other is registration without a central list: let every source file contribute entries to one section, and let the program walk the whole section at run time. This post demonstrates both on GCC 14 and GNU ld from binutils 2.42, using ELF on Linux, and covers the three problems that make a custom section vanish or misbehave.
The basics
The attribute takes a section name as a string:
int config_value __attribute__((section(".myconfig"))) = 42;
__attribute__((section(".myfuncs")))
int helper(int x)
{
return x + 1;
}Compile it and list the sections:
gcc -O2 -c sec1.c -o sec1.o
objdump -h sec1.o | grep -E 'myconfig|myfuncs' 3 .myconfig 00000004 0000000000000000 0000000000000000 00000070 2**2 CONTENTS, ALLOC, LOAD, DATA
4 .myfuncs 00000004 0000000000000000 0000000000000000 00000080 2**4 CONTENTS, ALLOC, LOAD, READONLY, CODEThe two objects have their own sections, with flags the compiler inferred from what each holds: data in one, executable code in the other. Offsets and sizes will differ with your compiler. The linker will merge sections with the same name from different object files, in link order, and its default script keeps unknown sections and places them after the known ones.
The compiler infers the flags from the object. A const variable gets read-only flags, a function gets executable flags. If two objects in the same section disagree, you get an error such as section type conflict, so keep one kind of thing per section. On the other platforms the syntax differs; Mach-O uses "__DATA,__mysection" with a segment and a section name, and Windows uses #pragma section and __declspec(allocate).
Pattern 1: a self-registering table
The most useful trick is a table that every file adds to. The kernel uses it for initcalls and for exception tables, and command-line tools use it for subcommands. Define a struct, then give each entry the same section attribute in whichever file defines it:
#ifndef CMD_H
#define CMD_H
struct cmd {
const char *name;
int (*run)(void);
};
#define REGISTER_CMD(fn, label) \
static const struct cmd cmd_##fn \
__attribute__((section("cmds"), used)) = { label, fn }
#endifTwo details deserve explanation. The section name is cmds without a leading dot, a valid C identifier, which makes GNU ld define two symbols automatically: __start_cmds at the first byte and __stop_cmds just past the last. And used tells the compiler to emit the static variable even though no code references it. Now two files add commands:
#include "cmd.h"
static int hello(void) { return 11; }
REGISTER_CMD(hello, "hello");#include "cmd.h"
static int status(void) { return 22; }
REGISTER_CMD(status, "status");The main program walks the section between the two symbols:
#include <stdio.h>
#include "cmd.h"
extern const struct cmd __start_cmds[];
extern const struct cmd __stop_cmds[];
int main(void)
{
int total = 0, count = 0;
for (const struct cmd *c = __start_cmds; c < __stop_cmds; c++) {
total += c->run();
count++;
}
printf("commands=%d total=%d\n", count, total);
return 0;
}gcc -O2 main.c a.c b.c -o app && ./appcommands=2 total=33Adding a third command in a new file needs no change to main.c or to a header list. The section grows, and __stop_cmds moves. The order of entries follows the link order of the object files, so never depend on it. Sort the table at start-up if you need a stable order, as the output here deliberately avoids printing names in sequence.
Pattern 2: placing code and data for the hardware
On a microcontroller, the linker script defines memory regions and assigns sections to them. The attribute names a section, and the script decides where it lives:
__attribute__((section(".ramfunc"), noinline))
void flash_write_word(volatile unsigned *addr, unsigned value)
{
*addr = value;
}A matching fragment of a GNU linker script puts those functions into RAM, loads them from flash and exports symbols the startup code uses to copy them:
.ramfunc : ALIGN(4)
{
__ramfunc_start = .;
*(.ramfunc*)
. = ALIGN(4);
__ramfunc_end = .;
} > RAM AT> FLASH
__ramfunc_load = LOADADDR(.ramfunc);The startup code then copies the bytes from __ramfunc_load to __ramfunc_start, as it does for .data. This is how flash-erase routines run while the flash is busy. The same pattern places a DMA buffer in a non-cached memory region with section(".dma_buffer"), and a lookup table in the faster tightly coupled memory.
Why a custom section disappears
Three things delete or hide your objects, and each has a specific cure.
The compiler removes unreferenced statics. A static variable nothing uses is dead code, and GCC drops it. Add __attribute__((used)), as above. Note that used stops the compiler from discarding the symbol, not the linker.
The linker garbage-collects the section. With -Wl,--gc-sections, a section no live code refers to is dropped. The table is referenced by the code that uses __start_cmds, but the individual entries are not referenced from anywhere except through the start and stop symbols, and older toolchains could discard individual input sections. GCC 11 and binutils 2.36 added the retain attribute and the SHF_GNU_RETAIN section flag for exactly this case: __attribute__((section("cmds"), used, retain)). On older toolchains, use the KEEP(*(cmds)) directive in a custom linker script, or avoid --gc-sections for that link.
The name has a dot. A section named .cmds does not get __start_ and __stop_ symbols from GNU ld, because the names must be valid C identifiers. With a dotted name you must define the bounds in a linker script, with PROVIDE(__start_cmds = ADDR(.cmds)) and a matching stop symbol. LLVM's lld supports the same implicit symbols for identifier-like names.
A related issue is LTO: with -flto, the compiler may partition and reorder objects, and used plus retain is the portable way to keep table entries. Prefer a test that counts the entries at start-up, which turns a silent loss into a visible failure.
Checking the result
After linking, confirm the section exists and the symbols bracket it:
nm app | grep -E '__start_cmds|__stop_cmds'
readelf -S app | grep -A1 ' cmds'0000000000004010 D __start_cmds
0000000000004030 D __stop_cmds
[24] cmds PROGBITS 0000000000004010 00003010
0000000000000020 0000000000000000 WA 0 0 8The span between the symbols, 0x20, is 32 bytes, two 16-byte entries. Addresses are examples. If the span is zero, the entries were dropped before the link finished, and you should check used and retain. Tools such as size -A and objdump -h list every section with its size, which is a quick audit of a firmware image.
Section names, flags and the sections you should not touch
Pick names that cannot collide with the toolchain. The compiler and linker already use .text, .data, .bss, .rodata, .init_array, .fini_array, .eh_frame and the .text.*, .data.* and .rodata.* families that -ffunction-sections creates. A custom name that begins with one of those prefixes can be merged into the standard section by the default linker script, which defeats the point. Choose a distinct prefix for your project, such as myproj_cmds, and the default script will treat it as an orphan section and place it sensibly.
If you need a section to carry particular flags that the compiler would not infer, GCC accepts a third form of the attribute through the assembler directive, for example asm(".section mytable,\"aw\",@progbits"), which sets the writable and allocated flags explicitly. Use this only when the inferred flags are wrong, since it ties the code to the ELF assembler syntax. Finally, remember that the section keeps its contents through the whole run unless the linker script marks it NOLOAD or places it at an address outside the image, which is how you reserve a region for a bootloader hand-off block.
When not to use it
A section table hides control flow: a reader looking at main.c cannot see which commands exist. Use it where the benefit is real, such as plugin registries and driver tables, and write one line of documentation at the macro. For runtime-extensible registration, a function with an explicit register_cmd() call and a static array is more readable and works on every compiler. The attribute is a GNU extension, so portable code needs a fallback for other compilers.


