Languages/C/Sections

From UIT
(Difference between revisions)
Jump to: navigation, search
(Program sections, or what are .text, .data, .bss?)
 
(One intermediate revision by one user not shown)
Line 31: Line 31:
 
|-  
 
|-  
 
|}
 
|}
 +
 +
== Not so universal sections ==
 +
{|class=wikitable
 +
|-
 +
| '''Section''' || '''Description'''
 +
|-
 +
| <code>.common</code> || Global uninitialized data, WARNING : the linker will merge variable with same names!
 +
|}
 +
== Example ==
 +
<source lang='c'>
 +
#include <stdio.h>
 +
 +
int a = 0; // .bss
 +
int b = 1; // .data
 +
int c; // .common
 +
const int d = 3; // .rodata
 +
 +
int main(int argc, char *argv[])
 +
{
 +
int e; // This one is on the stack !
 +
const int f = 5; // This too
 +
 +
/* Make the compiler happy by initializing uninitialized variables*/
 +
c = 2;
 +
e = 4;
 +
 +
return printf("a = %d, b = %d, c = %d, d = %d, e = %d, f = %d\n", a, b, c, d, e, f);
 +
}
 +
</source>

Latest revision as of 13:19, 16 December 2013

Contents

Program sections, or what are .text, .data, .bss?

When a program is compiled, the compiler splits the resulting code into different sections (sometimes called segments). Every section corresponds to a particular use, for instance storing variables or executable code.

This document is mainly focused on the ELF (Executable and Linkable Format) file format used by Linux and the gcc toolchain, but most of this document is valid for most executable file formats.

Here are some reason why there are separate sections:

  • Code and data can be on separate buses (Harvard architecture).
  • Code could be read-only and your system can have read-only memory (flash on microcontroller).
  • Code can be shared between 2 processes but data can't.

Sections can also have permissions like read, write, execute.

Universal sections

Section Description
.text Executable (machine) code
.data Initialized data
.bss Data initialized to zero
.rodata Read-only

Not so universal sections

Section Description
.common Global uninitialized data, WARNING : the linker will merge variable with same names!

Example

#include <stdio.h>
 
int a = 0;				// .bss
int b = 1;				// .data
int c;					// .common
const int d = 3;		// .rodata
 
int main(int argc, char *argv[])
{
	int e;				// This one is on the stack !
	const int f = 5;	// This too
 
	/* Make the compiler happy by initializing uninitialized variables*/
	c = 2;
	e = 4;
 
	return printf("a = %d, b = %d, c = %d, d = %d, e = %d, f = %d\n", a, b, c, d, e, f);
}
Personal tools
Namespaces
Variants
Actions
Navigation
Browse
Toolbox