0

This is a general C or C++ code related question. Why would you need the static keyword for a global variable in C or C++ if it is already global throughout the program and if this program is only using one file.

0

1 Answer 1

4

A global variable has external linkage by default. Meaning, it can be accessed by other translation units by using extern.

Declaring a global variable as static gives it internal linkage. Meaning, it can only be accessed within the translation unit that it is declared in, extern can't reach it.

If the program only has 1 translation unit (.c/.cpp file), declaring a global variable in that unit as static doesn't make any difference. But, if you have multiple translation units, it starts to make more sense to declare globals as static when you don't want to share them across translation units.

See https://en.cppreference.com/w/c/language/storage_duration for more details.

Sign up to request clarification or add additional context in comments.

1 Comment

I see, most of my programs are using only 1 .cpp file, along with .hpp header files as needed so I don't need the static keyword for global variables for now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.