简体   繁体   中英

Extern and const in C++

I've seen several posts about this issue, but none of them explains well my concern, so I'll try to explain here what I understand and please correct me if I'm wrong.

Suppose I have a header file with the following declaration:

//definitions.h
extern const float fallingTime; 

Now, I have two source files that want to use this declaration.

//source1.cpp
#include "definitions.h"
const float fallingTime = 0.5f;
//use fallingTime 

//source2.cpp
#include "definitions.h"
//just use fallingTime (no definition required)

This is what I do; but now, assume this other way to proceed.

//definitions.h
const float fallingTime = 0.5f; //Note that I don't use extern now

//source1.cpp
#include "definitions.h"
//just use fallingTime (no definition required)

//source2.cpp
#include "definitions.h"
//just use fallingTime (no definition required)

As I concluded from reading several sources, the advantages of the former approach is that it saves memory and compilation time, because memory allocation only occurs one (in the definition in source1.cpp), whereas in the latter approach memory allocation happens in every source file that includes definitions.h (source1.cpp and source2.cpp). Is that correct?

Finally, what would imply using extern and defining the constant at the same time? Would be equivalent to the former approach?

//definitions.h
extern const float fallingTime = 0.5f;

When const float fallingTime = 0.5f; is defined in a header, a translation unit may or may not store the value in the data section of your binary.

If no code in a translation unit takes an address or reference to fallingTime there is no reason for the compiler to allocate the value in the data section at all. The compiler is likely to replace usage of fallingTime with its value because its definition is available in every translation unit at compile time.

With extern const the generated code will have to load the value of fallingTime from memory because its definition is not available at compile time in any other translation unit but the one that defines the value of fallingTime .

The problem with the latter one is that under C++ prior to C++11 depending on your compiler, you could get a linktime error as there's no address for fallingTime. The language requires that you instantiate it in precisely one translation unit and gcc in particular is quite strict about that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM