skip to Main Content

I’ve been playing around my code editor and accidentally made this. This compiles fine, and works as intended. For additional context, I’m using GCC on Debian 11. As for how I knew the prototypes, VS Code’s IntelliSense told me.

Why does it work, and how? Neither <stdio.h> nor <math.h> is included.

double pow(double _x, double _y);
int printf(const char *__restrict__ __format, ...);

int main(void)
{
    printf("%fn", pow(2, -1));
}

Output: 0.500000

3

Answers


  1. You can declare your functions like you did or by including the relevant header file(s) (preferred). gcc will link in the definitions found in libc unless you tell it not to (with -nolibc)

    Login or Signup to reply.
  2. The standard library is linked into most C projects. If you created a standard project, your IDE most likely took care of that part for you in the background.

    Depending on how the compiler is configured, it may drag the functions in from the libc if they are defined as well. This allows a bit of optimization.

    The header files tell your program how to access those functions. If the library is linked, then all of its functions are there, whether the header file is or not. You didn’t magically bypass anything or anything like that. You just provided an alternative declaration of the function.

    Login or Signup to reply.
  3. It works because the C standard explicitly requires it to work.

    7.1.4 Provided that a library function can be declared without reference to any type defined in a header, it is also permissible to declare the function and use it without including its associated header.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search