在C和C++中,当两个文件中对同一函数和全局变量进行不同的声明时,我有两个问题。
Different function declarations
Consider the following code fragments:
file_1.c
void foo(int a); int main(void) { foo('A'); }
file_2.c
#include <stdio.h> void foo(char a) { printf("%c", a); //prints 'A' (gcc) }
As we can see, the prototype differs from the definition located in file_2.c, however, the function prints expected value.
If it comes to C++, the above program is invalid due to undefined reference to
foo(int)
at link time. It's probably caused by presence of other function signatures - in comparison with C, where a function name doesn't contain any extra characters indicating the type of function arguments.But when it comes to C then what? Since the prototypes with the same name have the same signature regardless of the number of arguments and its types, linker won't issue an error. But which type conversions are performed in here? Does it look like this:
'A'
->int
-> back tochar
? Or maybe this behavior is undefined/implementation-defined ?Different declarations of a global variable
We've got two files and two different declarations of the same global variable:
file_1.c
#include <stdio.h> extern int a; int main(void) { printf("%d", a); //prints 65 (g++ and gcc) }
file_2.c
char a = 'A';
Both in C and C++ the output is 65.
Though I'd like to know what both standards say about that kind of situation.
In the C11 standard I've found the following fragment:
J.5.11 Multiple external definitions (Annex J.5 Common extensions)
There may be more than one external definition for the identifier of an object, with or without the explicit use of the keyword extern; if the definitions disagree, or more than one is initialized, the behavior is undefined (6.9.2).Notice that it refers to presence of two and more definitions, in my code there is only one, so I'm not sure whether this article is a good point of reference in this case...