This question has already been answered:

looked at the source code iostream and there is such a construction

namespace std { extern istream cin; extern ostream cout; extern ostream cerr; extern ostream clog; } 

I tried to do the same:

 class AA { public : ... }; class BB { public : ... }; namespace OO { extern AA test1; extern BB test2; } 

but each time it compiles, it throws out something like that — an undefined reference to OO :: test1. If you do without extern, it will knock out a multiple definition. Tell me how to solve this problem? thank.

Reported as a duplicate by VTT members, Abyx c ++ Apr 8 at 5:48 pm

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • one
    Possible duplicate question: Link to unresolved external symbol (possible reasons) In general, this should not be done - it is better to implement a full-fledged singleton. - VTT
  • I just have such a task: to merge several classes into one "module", the implementation of iostream seemed to me quite acceptable. - Jone Green
  • The code above does not merge several classes into one “module”; it simply declares several global variables that must be defined in a translation unit. - VTT
  • one
    "which must be defined in some broadcast unit" you have not defined them. And if you write without extern, then they will be defined more than once - in each translation unit in which this header file is included. - VTT
  • one
    You need in some .cpp file to write a namespace OO {AA test1; BB test2;} namespace OO {AA test1; BB test2;} , not forgetting to make a header with class definitions. Or another option: Replace extern to inline . - HolyBlackCat 5:14

1 answer 1

In <iostream> you only see the declarations of global objects. And somewhere in the depths of the standard library sit their definitions .

In your code, you only reproduced the ads, but did not provide definitions at all. Here is the linker error: definitions not found.

You should choose some single unit of translation of your project and there additionally provide also definitions for these objects.

 OO::AA test1; OO::BB test2; 

If you don't care exactly where these objects will be defined, then in modern C ++, you can simply write directly in the header file

 namespace OO { inline AA test1; inline BB test2; } 

This will be both a declaration and a definition and, thanks to inline , will not cause multiple definition errors.