I found this line in stdio.h :
extern struct _IO_FILE *stdin;
Based on this 'extern' keyword, i assume this is just a declaration. I wonder where is stdin defined and initialized?
It's defined in the source code of your C library. You typically only need the headers for compilation, but you can find the source code for many open-source standard libraries (like glibc).
In glibc, it's defined in libio/stdio.c as like this:
_IO_FILE *stdin = (FILE *) &_IO_2_1_stdin_;
Which is in turn defined using a macro in libio/stdfiles.c like this:
DEF_STDFILE(_IO_2_1_stdin_, 0, 0, _IO_NO_WRITES);
The definition of the DEF_STDFILE macro varies depending on a few things, but it more or less sets up an appropriate FILE struct using the file descriptor 0 (which is standard input on Unix).
The definition may (and of course does) vary depending on your C library, and certainly by platform. If you want, you can continue the goose chase around the various parts of your standard library's I/O component.
The C standard explicitly states that stdin is a macro defined in stdio.h. It is not allowed to be defined anywhere else.
C11 7.21.1
"The header <stdio.h> defines several macros, ..." /--/
"The macros are..." /--/
stderr
stdin
stdout
which are expressions of type ‘‘pointer to FILE’’ that point to the FILE objects
associated, respectively, with the standard error, input, and output streams.
This macro can of course point at implementation details that are implemented elsewhere, such as in a "stdio.c" or whatever the compiler library chose to put it.
I believe it's defined in stdio.c which is compiled into in libc (on gnu based systems)
The definition will be implementation dependent, as will where you find it. For me, on OSX 10.6, it's defined in stdio.h, as a FILE (a struct).
stdin is of the type _IO_FILE, a struct which is clearly defined somewhere, probably in stdio.h. If not, check in the header files included in stdio.h for a definition of _IO_FILE.
In the standard library code, where else? In a Linux machine around here it's in libc.a:stdio.o, found using nm -o /usr/lib/libc.a | grep stdin | grep D. If you want to read some code, see the GNU C Library.
Related
I'm new to C and have read that each function may only be defined once, but I can't seem to reconcile this with what I'm seeing in the console. For example, I am able to overwrite the definition of printf without an error or warning:
#include <stdio.h>
extern int printf(const char *__restrict__format, ...) {
putchar('a');
}
int main() {
printf("Hello, world!");
return 0;
}
So, I tried looking up the one-definition rule in the standard and found Section 6.9 (5) on page 155, which says (emphasis added):
An external definition is an external declaration that is also a definition of a function (other than an inline definition) or an object. If an identifier delared with external linkage is used in an expression [...], somewhere in the entire program there shall be exactly one external definition for that identifier; otherwise, there shall be no more than one.
My understanding of linkage is very shaky, so I'm not sure if this is the relevant clause or what exactly is meant by "entire program". But if I take "entire program" to mean all the stuff in <stdio.h> + my source file, then shouldn't I be prohibited from redefining printf in my source file since it has already been defined earlier in the "entire program" (i.e. in the stdio bit of the program)?
My apologies if this question is a dupe, I couldn't find any existing answers.
The C standard does not define what happens if there is more than one definition of a function.
… shouldn't I be prohibited…
The C standard has no jurisdiction over what you do. It specifies how C programs are interpreted, not how humans may behave. Although some of its rules are written using “shall,” this is not a command to the programmer about what they may or may not do. It is a rhetorical device for specifying the semantics of C programs. C 2018 4 2 tells us what it actually means:
If a “shall” or “shall not” requirement that appears outside of a constraint or runtime-constraint is violated, the behavior is undefined…
So, when you provide a definition of printf and the standard C library provides a definition of printf, the C standard does not specify what happens. In common practice, several things may happen:
The linker uses your printf. The printf in the library is not used.
The compiler has built-in knowledge of printf and uses that in spite of your definition of printf.
If your printf is in a separate source module, and that module is compiled and inserted into a library, then which printf the program uses depends on the order the libraries are specified to the linker.
While the C standard does not define what happens if there are multiple definitions of a function (or an external symbol in general), linkers commonly do. Ordinarily, when a linker processes a library file, its behavior is:
Examine each module in the library. If the module defines a symbol that is referenced by a previously incorporated object module but not yet defined, then include that module in the output the linker is building. If the module does not define any such symbol, do not use it.
Thus, for ordinary functions, the behavior of multiple definitions that appear in library files is defined by the linker, even though it is not defined by the C standard. (There can be complications, though. Suppose a program uses cos and sin, and the linker has already included a module that defines cos when it finds a library module that defines both sin and cos. Because the linker has an unresolved reference to sin, it includes this library module, which brings in a second definition of cos, causing a multiple-definition error.)
Although the linker behavior may be well defined, this still leaves the issue that compilers have built-in knowledge about the standard library functions. Consider this example. Here, I added a second printf, so the program has:
printf("Hello, world!");
printf("Hello, world!\n");
The program output is “aHello, world.\n”. This shows the program used your definition for the first printf call but used the standard behavior for the second printf call. The program behaves as if there are two different printf definitions in the same program.
Looking at the assembly language shows what happens. For the second call, the compiler decided that, since printf("Hello, world!\n"); is printing a string with no conversion specifications and ending with a new-line character, it can use the more-efficient puts routine instead. So the assembly language has call puts for the second printf. The compiler cannot do this for the first printf because it does not end with a new-line character, which puts automatically adds.
Please aware of declaration and definition. The term are totally different.
stdio.h only provide the declaration. And therefore, when you declare/define in your file, as long as the prototype is similar, it is fine with this.
You are free to define in your source file. And if it is available, the final program will link to the yours instead of the one in library.
I'd like to look up all the functions, constants and types defined in C libraries: stdlib.h, stdio.h, ctype.h etc. So, when in C program I do: #include <stdlib.h> or #include <stdio.h> I'd like to know what are all the functions, constants and types I get with that?
What's the easiest way to do this locally on the computer? I'm not so much interested in online references, especially if they're not official.
Is there a manpage that lists this for eg stdlib? Does maybe GNU info program have docs for this? Or do I have to find an actual header file and look it up?
I'd prefer an universal approach, but if it differs from system to system I'm curious how to do that on both Mac and Linux?
When you include one of the standard C headers, at least three types of identifiers may be declared:
Identifiers specified by the C standard. The authoritative source for information on these is the C standard, plus documentation for the C implementation you are using.
Identifiers for extensions to the C language. For example, the headers may declare identifiers for POSIX functions. The headers might declare such identifiers only if you have requested them by defining certain preprocessor symbols before including the headers.
Identifiers for internal use of the C implementation. These identifiers commonly begin with an underscore followed by another underscore or a caputal letter, as the C standard reserves those. You can discover these identifiers by examining the actual header files in your C implementation, but you should not use them unless documentation for your implementation offers them for use.
Overall, if you want to know what C provides in the standard headers, you should read either the C standard (for authoritative information) or a good C textbook (for tutorial information). If you want to know what else is in the headers, there is a large variety of things that an implementation could put into the headers, so the way to find out what is there is to read the documentation for the implementation and/or to examine the header file and then find the documentation for the extra things it provides, such as the POSIX documentation.
You asked for sources on your computer. Your C implementation may come with documentation, and Unix includes documentation accessible via the man command. While you can examine the actual header files, it is important to understand the current contents of the headers do not constitute any promise about future behavior. Any internal identifiers may change in future versions, and the behavior of standard identifiers may change as permitted by the C standard.
Your terminology stdlib is not well-defined. There's a "Standard I/O Library" as part of the C Programming Language, and a stdlib.h header file.
For C identifiers, here's an overview for ISO C and POSIX identifiers.
Apart from that, you can look at the symbols in library files with
nm -AP /path/to/libfoobar.a
Update
To inspect a header in the form the compiler sees it, look at the result of preprocessing (-E):
$ gcc -E /usr/include/stdlib.h|less
typedef unsigned char __u_char;
typedef unsigned short int __u_short;
typedef unsigned int __u_int;
typedef unsigned long int __u_long;
[...]
typedef struct
{
int quot;
int rem;
} div_t;
typedef struct
{
long int quot;
long int rem;
} ldiv_t;
[...]
extern long int random (void) __attribute__ ((__nothrow__ , __leaf__));
[...]
Going through the K&R ansi C programming language book (second version), on page 82 an example is given for a programming files/folders layout.
What I don't understand is, while calc.h gets included in main (use of functions), getop.c (definition of getop) and stack.c (definition of push and pop), it does not get included into getch.c, even though getch and ungetch are defined there.
Although it's a good idea to include the header file it's not required as getch.c doesn't actually use the function declared in calc.h, it could even get by if it only used those already defined in getch.c.
The reason it's a good idea to include the header file anyway is because it would provide some safety if you use modern style prototypes and definitions. The compiler should namely complain if for example getop isn't defined in getop.c with the same signature as in calc.h.
calc.h contains the declaration of getch() and ungetch(). It is included by files that want to use these functions (and, therefore, need their signature).
getch.c, instead, contains the definition of getch() and ungetch(). Therefore, there is no need of including their declaration (which is implicitly defined in the definition).
The omission you have so aptly discovered can be a source of a real problem. In order to benefit fully from C's static type checking across a multi-translation-unit program (which is almost anything nontrivial), we must ensure that the site which defines an external name (such as a function) as well as all the sites which refer to the name, have the same declaration in scope, ideally from a single source: one header file where that name is declared.
If the definition doesn't have the declaration in scope, then it is possible to change the definition so that it no longer matches the declaration. The program will still translate and link, resulting in undefined behavior when the function is called or the object is used.
If you use the GNU compiler, you can guard against this problem using -Wmissing-prototypes. Straight from the gcc manual page:
-Wmissing-prototypes (C and Objective-C only)
Warn if a global function is defined without a previous prototype
declaration. This warning is issued even if the definition itself
provides a prototype. The aim is to detect global functions that
fail to be declared in header files.
Without diagnosis, this kind of thing, such as forgetting a header file, can happen to the best of us.
One possible reason why the header was forgotten is that the example project uses the "one big common header" convention. The "one big common header" approach lets the programmer forget all about headers. Everything just sees everything else and the #include "calc.h" which makes it work is just a tiny footnote that can get swallowed up in the amnesia. :)
The other aspect is that the authors had spent a lot of time programming in pre-ANSI "Classic" C without prototype declarations. In Classic C, header files are mainly for common type declarations and macros. The habit is that if a source file doesn't need some type or macros that are defined in some header, then it doesn't need to include that header. A resurgence of that habit could be what is going on here.
When I am going through a code snippet I have seen some functions like
#include <stdio.h>
int main() {
printf( "Upper case of a is %c\n", toupper('a'));
printf( "Upper case of 9 is %c\n", toupper('9'));
printf( "Upper case of g is %c\n", toupper('g'));
return 0;
}
being used in the source file without any header file being included.
So is there any default header file that gets added to source when compiling. I am using GNU C.
Please don't mind if the syntax of the function is wrong as that is not the important point.
No, there are no implicit #include directives.
What you're probably running into is that, prior to the 1999 ISO C standard, C permitted functions to be called with no visible declaration. The compiler would assume that the called function returns int and takes arguments compatible with the (promoted) arguments passed in the call.
gcc by default supports the 1990 ISO C standard plus GNU-specific extensions.
If you compile with something like gcc -std=c99 -pedantic, you'll get warnings about calls to functions with no visible declarations. (Use -std=gnu99 if you need GNU-specific extensions as well.)
Calling undeclared functions was a bad idea even before the 1999 standard. You should correct your code so there's a visible declaration (probably via a #include for the appropriate header) for each function you call or otherwise refer to.
Your original question asked about toUppercase, which is not a standard function; it may or may not be defined somewhere else.
Your revised question uses toupper, which is a standard C function declared in <ctype.h> and defined in the standard C library.
It's not surprising that you can get away with calling toupper with no visible declaration -- but you should still add
#include <ctype.h>
to the top of your source file.
Before you do that, try compiling with gcc -std=c99; you should get a warning.
One more thing: It's important to keep in mind that headers and libraries are two different things.
Headers, like <stdio.h> and <stdlib.h> are generally text files containing just declarations of functions and other entities specified by the C standard library.
Libraries, which have system-specific names like, for example, libc.so, contain the actual executable code that implements those functions.
Headers are handled by the compiler; libraries are handled by the linker.
There are generally no default headers; every header you use has to be explicitly #included, either directly or indirectly. libc.so (or whatever it's called) is typically linked by default; you don't have to specify it. (Though for the functions declared in <math.h>, you often have to specify -lm to link the corresponding library.)
As forum people are asking not to discuss in comments so i have no other option than replying to " Keith Thompson" last post. I am not sure what you meant by c standard library. look here
C standard library
It clearly says 27 header files are part of standard library and stdlib.h is one of them. See my point is not to argue with you. I am trying to have clarity in mind. You are saying something like libc.so as standard library but the wikipedia clearly states something else and now i am totally confused.
When I create a simple C program in Visual Studio 2010,
http://debugmode.net/2012/02/06/how-to-write-and-run-a-c-program-in-visual-studio-2010/
I remove the "#include < stdio.h > ",
My program still runs successfully, I could not understand how is it possible?
Any help is appreciated.
Regards,
The stdio.h header isn't strictly required unless you use functions declared in it, such as the following:
http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.12.html
Further looking at the code I believe the default behaviour when you don't have a prototype is to assume an int return type and to derive the types of parameters from the types of arguments which will work in this particular case. But it's generally a bad practice and should be avoided.
If that passed through the compiler / linker without any warnings you may want to check your environment settings. It's easy to forget to include an header and it can cause a lot of unintended and hard to track down side effects if you don't notice it.
The primary purpose of including standard header files is to include the declarations of standard functions into your source file.
However, the original standard C language (C89/90) did not require functions to be declared before they are called (aside from variadic functions, which have to be pre-declared with prototype to avoid undefined behavior). For this reason, as long as we are talking about non-variadic function calls, it is perfectly possible to write a correct program without pre-declaring standard functions, i.e. without including standard header files.
For example, calling strcmp function with two char * arguments is perfectly legal in C89/90 without pre-declaring strcmp. Meanwhile, printf has to be pre-declared with prototype, if you want your program to remain a valid C program with defined behavior.
This header file provides prototypes for a number of common functions and macros.
If you don't call any of those functions or macros, then you don't need it. If you do call them, it can still work as long as you are linking with the right libraries. But you could get some compiler errors or warnings if the compiler doesn't have those definitions.
#include < stdio.h >
It is a header file known as standard input output file. The input,output funcation are written in this file. funcations like printf,scanf etc.
Refere this http://computer.howstuffworks.com/c2.htm