Yesterday, I have been watching discussion here, about compilers and linkers. It was about C library function definitions. I have never thought of that, so it inspired me to do some searching, but I cannot find exactly what I want. I wonder, what is the smallest syntax you need to add into your source code to enable just printf() function. I mean the function declaration from stdio.h you need.
The definition is usually compiled in a shared library. The declaration is what you need. Not having a declaration in scope invokes undefined behavior. So, for every library, you'd typically have a (set of) header file(s) and the compiled binary shared/static library. You compile your sources by including appropriate headers and link with the library. To bring in the declaration in scope use the #include
directive. E.g. for printf
you'd do:
#include <stdio.h>
int main() {
printf("Hello, world\n");
return 0;
}
But then any decent book on C or C++ should already cover this in detail and with better examples.
The C99 declaration of printf()
is
int printf(const char *restrict, ...);
but most compilers will also accept
int printf(const char *, ...);
See also C99 section 7.1.4, §2:
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.
Note: In this case, the restrict
qualifier combined with const
promises the compiler that the format string is never modified within printf()
, even if the pointer is passed again as one of the variadic arguments.
It depends on your compiler and platform.
On most cases just declaring
int printf(const char *, ...);
will just do, however, your particular compiler/platform or C library implementation even can change this declaration, for calling convention purposes.
All in all it is not worth it to try and declare things yourself, as this could be a violation of the one definition rule. You should always include the apropriate header, stdio.h(cstdio for C++) in this case.