简体   繁体   中英

C/C++ definitions of functions

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 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.

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. Eg 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM