3

Let's say we want to create a socket using the "socket"-function. How does the compiler know that it has to invoke a system call for that corresponding function? Is there any internal table that records with functions belong to a specific set of library?

NHSH
  • 69
  • 7
  • 3
    Either the compiler knows no such thing and simply compiles a call to this function in the standard C library, which consists of machine language code that executes this system call; or the compiler just knows that `socket()` is a system call and how to make it. The compiler just knows. It's very smart, like that. – Sam Varshavchik Dec 22 '20 at 17:16
  • Okay, makes sense. Thank you! – NHSH Dec 22 '20 at 17:17
  • It doesn't. Syscalls are typically made through wrapper function provided by your standard c library. The compiler then just calls `ssize_t write(int,void const*,size_t);` or any other sycall wrapper like it would call any other function, regardless of whether the instructions in it make a syscall or not. – Petr Skocik Dec 22 '20 at 17:18
  • Yes, this was my initial guess, for in c# for example, you use the keyword "extern" that has an "dllimport"-attribute. Thanks. – NHSH Dec 22 '20 at 17:21
  • @ChezBorz `dllimport` is a Windows, which isn't really needed. UNIX toolchains and even some on Windows do without it. A call to a declared function just leaves a marked hole in the assembly, which the linker plugs up, either with a static libary (/an object file) or by linking with a dll/dso. Again, the mechanism is the same regardless of what's inside the linked function. – Petr Skocik Dec 22 '20 at 17:25
  • Some quick-and-helpful reading: [How does the compilation/linking process work?](https://stackoverflow.com/questions/6264249/how-does-the-compilation-linking-process-work) – user4581301 Dec 22 '20 at 17:51

1 Answers1

10

The usual method is this:

Your platform's library includes a function called socket that contains the actual code needed to make a system call on your platform. The compiler reads in a header file that tells it that this function exists, the linker connects the compiled code to that function, and the library's implementation of that function makes the actual system call.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278