开发者

C/C++ definitions of functions

开发者 https://www.devze.com 2022-12-23 02:26 出处:网络
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 c

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 syn开发者_JAVA技巧tax 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. 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消