1

This is file "1.c"

    #include <stdio.h>
    char foo;
    int bar(){
    }
    int main(){
        printf("%d",foo);
        return 0;
    }
    //--------------------------

This is file '2.c'

    void foo(){
    }

Compiler invoked as gcc 1.c 2.c

Does the above gives an undefined behaviour? My guess is, yes. Otherwise it's almost impossible to do optimization.

Multiple different definitions for the same entity (class, template, enumeration, inline function, static member function, etc.) [What are all the common undefined behaviour that a C++ programmer should know about?

But as far as I know char foo produce only a weak symbol that can be overridden by void foo(){} at linkage. Furthermore, if I change char foo into extern char foo, is that still a definition?

phoeagon
  • 2,080
  • 17
  • 20
  • Discussion of things like weak symbols goes beyond the scope of the C standard (and therefore it's not necessarily meaningful to ask whether "undefined behaviour" applies here)... – Oliver Charlesworth Apr 09 '13 at 00:02
  • extern char foo would only be a declaration and no definition. You can try to add it in 1.c (without 2.c), it should throws error during compilation – Marc Simon Apr 09 '13 at 00:08
  • I think you can get answer from http://stackoverflow.com/questions/2766022/linking-libraries-with-duplicate-class-names-using-gcc"Here" – MYMNeo Apr 09 '13 at 02:26

1 Answers1

2

It'd cause undefined behaviour, yes. There are probably lots of quotes from the standard that are explicit for the various types of declarations and so forth, but this sums it up:

In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. (6.2.2)

All declarations that refer to the same object or function shall have compatible type; otherwise, the behavior is undefined. (6.2.7)

char foo; in your example is a tentative definition. If you use extern, it would not be a definition, but it'd still be a declaration, and the above would still apply.

Community
  • 1
  • 1
teppic
  • 8,039
  • 2
  • 24
  • 37