Global Exterior Lightening

Declares extern const or just extern the same thing in the header file? Also will both give an external connection?

globals.cpp

#include <string>

extern const std::string foo = "bar";

globals.h

#ifndef GLOBALS_H
#define GLOBALS_H

#include <iostream>

extern const std::string foo;

#endif  /* GLOBALS_H */

OR

globals.h

#ifndef GLOBALS_H
#define GLOBALS_H

#include <iostream>

extern std::string foo;

#endif  /* GLOBALS_H */

Both compile and work fine, both give the same address when used in multiple files, which one is more correct?

+3
source share
4 answers

It's right,

//globals.h

extern const std::string foo; //Consistent

According!

+3
source

You can give const an external connection, as in your example, but it is still not modifiable (permanent). Postscript you need to enable <string>, not<iostream>

PPS If I were unclear, you cannot override a constant. This will not compile:

extern std::string foo;
extern const std::string foo = "bar";
+1

-

extern const std::string foo;

foo - , , extern , , , foo.

+1

, , , foo, , foo ( ). ( / - .:))

. , const, / , - foo.

( globals.cpp), globals.h foo (, "foo.c_str();" ), const std::string foo.

. , foo, , . , globals.h, , globals.cpp; , const, , .

+1

Source: https://habr.com/ru/post/1782456/


All Articles