Note that there are some explanatory texts on larger screens.

plurals
  1. PODifferent declarations of the same function/global variable in two files
    text
    copied!<p>I have 2 questions regarding different declarations of the same function and global variable in two files in case of C and C++ as well.</p> <ol> <li><p><strong>Different function declarations</strong></p> <p>Consider the following code fragments:</p> <p><strong>file_1.c</strong></p> <pre><code>void foo(int a); int main(void) { foo('A'); } </code></pre> <p><strong>file_2.c</strong></p> <pre><code>#include &lt;stdio.h&gt; void foo(char a) { printf("%c", a); //prints 'A' (gcc) } </code></pre> <p>As we can see, the prototype differs from the definition located in <strong>file_2.c</strong>, however, the function prints expected value.</p> <p>If it comes to C++, the above program is invalid due to undefined reference to <code>foo(int)</code> 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.</p> <p>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: <code>'A'</code> -> <code>int</code> -> back to <code>char</code>? Or maybe this behavior is undefined/implementation-defined ?</p></li> <li><p><strong>Different declarations of a global variable</strong></p> <p>We've got two files and two different declarations of the same global variable:</p> <p><strong>file_1.c</strong></p> <pre><code>#include &lt;stdio.h&gt; extern int a; int main(void) { printf("%d", a); //prints 65 (g++ and gcc) } </code></pre> <p><strong>file_2.c</strong></p> <pre><code>char a = 'A'; </code></pre> <p>Both in C and C++ the output is 65.</p> <p>Though I'd like to know what both standards say about that kind of situation.</p> <p>In the C11 standard I've found the following fragment:</p> <blockquote> <p><strong>J.5.11 Multiple external definitions</strong> <em>(Annex J.5 Common extensions)</em><br> 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).</p> </blockquote> <p>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...</p></li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload