Agrim Pathak
Agrim Pathak

Reputation: 3207

C++: Declaring non-global variables in header?

In the code below, y is used in func(). While the code compiles, in terms of convention and/or optimization, does y need to be declared in the header file? If so, is there anyway I can prevent y from appearing in every file that includes the header?

   //func.h
    #ifndef FUNC_H
    #define FUNC_H

    int func(const int x);

    #endif // FUNC_H
    //


    //func.cpp
    const int y = 5;

    int func(const int x)
    {
      return x + y;
    }
    //

Upvotes: 1

Views: 78

Answers (2)

Chris Drew
Chris Drew

Reputation: 15334

No, if y is only used in func.cpp then there is no need (in terms of convention or performance) to declare it in the header file. What you have looks fine to me.

A constant implicitly has internal linkage so it is only accessible inside func.cpp.

You could consider making it constexpr.

If y is only used in func() you could consider declaring it inside func(). I think to assume a global variable will perform better is premature optimization.

Upvotes: 1

radar
radar

Reputation: 13425

one option

In the header file have the declaration

extern const int y;

In one of the source files define the variable

const int y =5;

Upvotes: 0

Related Questions