C - One-definition rule for functions - c

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.

Related

Why are string functions working without including the string library?

In my code, I call functions from the string.h library (specifically, strcmp()), but I forgot to add the string library. Even without including the string library, my code compiles and runs properly as if I had included the string library.
What is happening?
A header file (e.g., string.h) only includes function declarations: that is, the return type and types and number of parameters.
The functions are defined in the C library (which is linked against your code by default), so they are are available to you whether or not you #include <string.h>. However, if you fail to #include the header file, the compiler might warn you about missing function declarations, and it can also cause problems if the return type of a function is other than int (the default for functions not otherwised declared in C).
Starting with the 1999 ISO C standard, calling a function with no visible declaration is a constraint violation, requiring a diagnostic. The diagnostic may be a non-fatal warning.
Some C compilers do not enforce the newer C99 rules by default. For example, until recently gcc's default behavior was -std=gnu89, which supports the 1989/1990 C standard with GNU-specific extensions.
Under the older rules, if you call a function with no visible declaration, an implicit declaration is created assuming that the function returns int and expects the number and types of arguments you've passed it. If that assumption is incorrect, the call's behavior is undefined. It happens that strcmp() returns an int, so if the compiler accepts the call you'll probably get away with it.
You should find out how to get your compiler to at least warn you about calls to undeclared functions. Once you've confirmed that it will do so, you should add the requires #include <string.h> to your code.
Note that the #include directive only includes the header file that declares strcmp and other standard functions, not the library. The definitions of those functions (the code that implements them) is commonly included as part of the C standard library. Linking your program to the standard library is handled by the linker, not by the compiler, and it's usually done implicitly (because you asked to compile and link a C program). (The math library, depending on the implementation, might not be linked automatically, but the implementation of the string functions almost always is.)
The string library is in fact included if you include the stdio library. But the stdio does not include the string library(not directly)
By default compiler include all necessary header file and program will successfully run.
Which Compiler you are using ?
you should use C99 compiler with -strict flags and -error flags then compiler will give you error if you call a function without including header file..
Error will look like this
implicit declaration of strcmp() found

Ansi C - programming language book of K&R - header file inclusion

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.

Is there any default header file in GNU

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.

C program without #include<stdio.h> in Visual Studio

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

C program is running without including Header files? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C program without header
I have been studying C for a long time . but one thing that bothering me is that , today I made a C program and forget to include the stdio.h and conio.h header files I saved the file as kc.c ? when I compiled and run this .c file the output was as I was expecting to be.
but how can a C program could run without using the standard header file?
or I am not aware with the concepts that I am missing hear?
EDIT: the program
int main()
{
int i=12,j=34;
int *pa=&i,*pb=&j;
printf("the value of i and j is %d %d respectively ",*pa,*pb);
getch();
return 0;
}
because I have used the printf() function of STDIO.H header here ,but without including it how can It got compiled and run successfully?
The compiler is allowed to make things work, but is under no obligation to do so.
You are supposed to declare all variable argument list functions before using them; not declaring printf() properly leads to undefined behaviour (and one valid undefined behaviour is to work as expected).
You should be getting warnings about the undeclared functions if you compile in C99 mode (but Turbo C probably doesn't have a C99 mode).
Nit-picking:
[H]ow can a C program could run without using the standard header file?
All programs run without using any headers whatsoever. However, most programs are compiled using the standard headers to declare the standard functions, and the better programs ensure that all functions are declared before they are used (or are defined as static functions before they are used).
C99 requires this, though many compilers will allow errant programs to compile. However, the compilation should produce a diagnostic; the diagnostic may or may not lead to the compilation failing. In practice, it usually doesn't cause the compilation to fail, but it could and with some compilers (GCC, for example) you can force the compiler's hand (e.g. with GCC's -Werror=missing-prototypes -Werror=old-style-definition options).
When the language standard being applied pre-dates ISO C99, C does not require a function to be declared or defined before it is referenced.
However when the compiler encounters such a function call, it simply assumes that the function returns an int and that it takes an indeterminate number and type of parameters. This is called am implicit declaration. If you later declare the function, or call it with a different number of parameters or incompatible parameters, you may get a warning in some compilers that the second call does not match declaration implied by the first, but the ISO C89 standard treats the function as variadic [like printf()] where any number and type of parameters are allowed.
Moreover if the actual return value is not an int, any return value accepted and processed may not make much sense one way or another.
It is bad form to rely on an implicit declaration, and most compilers would issue a warning. If your compiler did not, you need to increase the warning level; those diagnostics are there to help improve your code quality. If you simply ignored the warning (any warning for that matter), then you shouldn't!
In C++ the rules are tighter and failure to declare or define a function before referencing it is an error, since it is necessary to allow function overloading.
A header file is nothing more than a listing of constants, preprocessor macros and function prototypes. The function prototypes tell C what arguments each function takes.
If the compiler sees a function being used without a corresponding prototype or function definition, it generates an implicit declaration of the form int func(). Since C functions are linked solely by name and not by function signature (as is the case with C++), the linker later locates the function definitions in the standard library.

Resources