Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compile C code to a raw os-less binary?

Considering that C is a systems programming language, how can I compile C code into raw x86 machine code that could be invoked without the presence of an operating system? (IE: You can assume I have a boot sector that loads the raw machine code from disk into memory then jumps directly to the first instruction).

And now, for bonus points: Ideally, I'd like to compile using Visual Studio 2010's compiler because I've already got it. Failing that, what's the best way to accomplish the task, without having to install a bunch of dependencies or having to make large sweeping configuration changes across my entire system? I'd be compiling on Windows 7.

like image 442
Nicholas Hill Avatar asked Oct 14 '13 17:10

Nicholas Hill


2 Answers

Usually, you don't. Instead, you compile your code normally, and then (either with the linker or some other tool) extract a raw binary from the object file.

For example, on Linux, you can use the objcopy tool to copy an object file to a raw binary file.

$ objcopy -O binary object.elf object.binary
like image 147
Chris Dodd Avatar answered Oct 25 '22 03:10

Chris Dodd


First off you dont use any libraries that require a system call (printf, fopen, read, etc). then you compile the C files normally. the major difference is the linker step, if you are used to letting the c compiler call the linker (or letting some gui do it) you will likely need to take over that manually in some form. The specific solution depends on your tools, you will need to have some bootstrap code (the small amount of assembly that is needed to cover the assumptions of C compilers and programmers and launch the entry point in your C program), and a linker script or the right command line options for the linker to control the address space for the binary as well as to link the objects together. Then depending on the output format of the linker you might have to convert it to some other binary format (intel hex, srec, exe, com, coff, elf, raw binary, etc) to be compatible with wherever it is going to be loaded or run.

like image 31
old_timer Avatar answered Oct 25 '22 02:10

old_timer