25

The code I'm working on is supposed to be possible to build for both hosted and freestanding environments, providing private implementations for some stdlib functions for the latter case.

Can I reliably test this with just GCC on a normal workstation/build server? Compile for freestanding environment with GCC

  • The "-ffreestanding" option looked promising, but it seems that it "only" disables built-ins and sets the STDC_HOSTED macro properly, it still provides all system headers.

  • The option "-nostdinc" is too restrictive; I still want to use the headers required for a freestanding implementation (in particular stddef.h and limits.h).

What am I missing here?

Oh, and I'm using GCC 4.4.3 for the moment, will upgrade to 4.5.0 "soon".

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Christoffer
  • 12,712
  • 7
  • 37
  • 53
  • Curious... why are you building for freestanding? Are you making one of those hardcore "/sbin" programs? Are you writing a kernel? I've only seen "-ffreestanding" mentioned in the context of custom Linux. – Michael Aaron Safyan Apr 21 '10 at 08:31
  • Short answer is market demand. Some of our customers on the embedded/mobile side wants our product to be completely self-contained. – Christoffer Apr 21 '10 at 08:40

2 Answers2

24

Well, since no answer is given yet I'd might as well describe how I made this work. It's pretty simple although depending on the target system it can be tedious.

Using "-nostdinc" means that the standard system include paths will be skipped; other include-paths given with "-I" will of course still be searched for headers.

So, for the freestanding build target I create a folder 'include-freestanding-c89' and link the relevant system headers -- float.h, iso646.h, limits.h, stdarg.h and stddef.h -- there. Other headers might be included in these, depending on your platform, so you might have to do some research and set up more links (hence the tediousness if you need to do this for several target platforms).

The C89 directory can then be used as base for 'include-freestanding-c99', the extra headers to link are stdbool.h and stdint.h

The command-line to use is then

gcc -std=c89 -nostdinc -nostdlib -ffreestanding -I include-freestanding-c89 

or

gcc -std=c99 -nostdinc -nostdlib -ffreestanding -I include-freestanding-c99
Christoffer
  • 12,712
  • 7
  • 37
  • 53
3

This Xen Makefile uses gcc -print-search-dirs to get the directory with stddef.h and similar, adds it with -isystem, then uses -nostdinc to build:

https://github.com/mirage/xen/blob/2676bc915157ab474ee478d929b0928cf696b385/stubdom/Makefile#L35

Thomas Leonard
  • 7,068
  • 2
  • 36
  • 40