c++constantsextern

C++ variable extern declarations


I have declared some constants in a header file:

extern int  g_iShortSize1FrameEncoded=30;
extern int  g_iByteSize1FrameEncoded=(g_iShortSize1FrameEncoded*2);
extern int  g_iShortSize1FrameDecoded=960;
extern int  g_iByteSize1FrameDecoded=(g_iShortSize1FrameDecoded*2);

This is really convenient for me because I need to use these "constants" in various apps and change them often, and I want to do this only once so that I don't forget to change anything.

It compiles fine.

However my declaration is a bit "wild".

I have to trust the compiler will compile it in the right way.

Is my approach fine anyway?

I will not change these values at runtime, only during development.

I have 3 different applications, and all consume / need these values.

In the applications I simply wanted to include them as

#include "..\..\myconstants.h"

Solution

  • Usually you'd just put this in header file:

    extern const int  g_iShortSize1FrameEncoded;
    extern const int  g_iByteSize1FrameEncoded;
    extern const int  g_iShortSize1FrameDecoded;
    extern const int  g_iByteSize1FrameDecoded;
    

    and this in .cpp file corresponding to that header:

    const int  g_iShortSize1FrameEncoded=30;
    const int  g_iByteSize1FrameEncoded=(g_iShortSize1FrameEncoded*2);
    const int  g_iShortSize1FrameDecoded=960;
    const int  g_iByteSize1FrameDecoded=(g_iShortSize1FrameDecoded*2);
    

    This way linker knows that variables are placed in one compilation unit and refers to them from other compilation units. Also note the const keyword -- you wrote that they are constants.