MistyD
MistyD

Reputation: 17223

More Multiply defined symbols

I was going over this article and it talks about the compile process (pre-process,compile,link). I understand that include guards simply solve the issue of preventing multiple inclusions in the same translation unit. So if I have the following scenario :

File : Common.h
----------------
#ifndef External_Header
#include "iostream"
#define External_Header
std::string R = "dsds";
#endif

Now I have two cpp files both of them include this header file. I understand why I get the linker error "fatal error LNK1169: one or more multiply defined symbols found". What I am curious about is why I dont get the same linker error when I define a struct instead of a string.

Any thoughts or ideas that might clarify this.

     File : Common.h
     ----------------
    #ifndef External_Header
    #include "iostream"
    #define External_Header
    struct mystruct
    {
        int a;
    };
    #endif

Upvotes: 0

Views: 106

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

It's because structs are not symbols.

The C++ standard explicitly allows us to redefine types in different translation units... as long as their definition doesn't change.

[C++11: 3.2/1]: No translation unit shall contain more than one definition of any variable, function, class type, enumeration type, or template.

[C++11: 3.2/3]: Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program; no diagnostic required. [..]

Notice how types are mentioned in the former rule but not the latter. This is made explicit a little later on:

[C++11: 3.2/5]: There can be more than one definition of a class type [..] in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. Given such an entity named D defined in more than one translation unit, then

  • each definition of D shall consist of the same sequence of tokens;
  • [..]

Cross-translation-unit programming would be impossibly difficult if it weren't for this distinction.

Upvotes: 1

jvh
jvh

Reputation: 362

The problem may be that you are creating a variable in the one case, but in the other case defining a new type. To verify this may try the following code.

struct mystruct
{
    int a;
} myTestVar;

Upvotes: 2

Related Questions