My question is originating from my lack of experience with lower level systems programming (particularly at the level of implementation of the OS). The executable contains some information for the operating system - for example which libraries it has to be dynamically linked to on start. So the compiler when compiling a file places such dependancies in the appropriate location in the executable. So we compile code for a given system. But then how do we compile the code that comprises the system? Which system does the compiler compile that code for?
The C programming language was developed to aid in writing the UNIX operating system, but what about say Linux?
Sorry for the rather chicken egg question.
Most C compilers have an option to not link against the system's standard C library. If you choose such a function, then standard functions like malloc, printf don't exist.
The only code you'll be able to call would be the code you create. No system includes, no standard library functions, nothing else but your own code. A blank slate.
There's a lot that goes into writing an operating system - threads, processes, protected memory, memory allocator, privilege separation, input/output, device access, file systems, networking... the list goes on.
As you write your operating system's kernel, you'll eventually have enough support structure that you can start writing user mode system calls to access your kernel's features such as file IO. If you choose to, you can do so by implementing them in the standard shape of the C standard library.
Theoretically, you could write an operating system that doesn't have a function called malloc, or printf. The C compiler won't care.
The trick here is to have a linker that can build the correct code. It's not the compiler.