I have a int vertexCount variable that’s initialized by reading a text file on a loader.cpp and I want to make it available to a separate model.cpp file.
Should I declare it as
extern vertexCount
on model.cpp? Or on a .h?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You forward-declare
extern int vertexCount;in the header where it is appropriate for this variable to be, and declare (i.e., allocate memory) in the .cpp:int vertexCount;. You can either initialize it immediately (int vertexCount = 1;) or later in the code in any of the files containing code (you’ll need to include the header, of course).It’s however your responsibility not to access the variable until it’s really initialized.
You can consider as well putting the variable into a class, which will ensure proper initialization in either constructor or on first access (you’ll need a kind of getter), or in the background, etc. This way is perhaps the cleanest.