Home > front end >  Why does this work? Being able to use a function from standard libraries by declaring the prototype
Why does this work? Being able to use a function from standard libraries by declaring the prototype

Time:11-22

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("%f\n", pow(2, -1));
}

Output: 0.500000

CodePudding user response:

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)

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • cgcc
  • Related