1

I'm pretty new to Visual Studio and I'm currently working on a project in which I want to use multiple .cpp files. Basically I want to make a function outside main.cpp in function.cpp and that function should be able to change global variables. Then I'd use that function in main.cpp.

I tried making a header named globals.h and putting static variables in it. I included globals.h in both main and function.cpp and it compiled but whenever I call that function in main it does absolutely nothing. When I try to include function.cpp in main.cpp I get multiple definition error while compiling.

What am I doing wrong? Thanks in advance!

1
  • 1
    could you show some code Commented Nov 3, 2011 at 11:27

2 Answers 2

4

Don't use static variables in header files. As headers are “incorporated” in compilation units, all variables declared as static in your header become scoped inside your compilation unit only. You won't be able to use the same global variable in your cpp files.

This is how your structure should be:

globals.h ------ extern int my_global_integer; main.cpp ------ #include "globals.h" // here use my_global_integer; function.cpp ------ #include "globals.h" // global variables have to be declared in exactly one compilation unit. // otherwise the linker will complain that the variable is defined twice. int my_global_integer = 0; 
Sign up to request clarification or add additional context in comments.

1 Comment

Did everything you said and it's working now, thank you very much :)
0

What did u mean by "trying to include function.cpp in main.cpp"? Are u trying to use the function.cpp's functions in main.cpp? In that case all u need to do is to include function.h in ur main.cpp file.

As for the error part, make sure u've provided the prototypes and data variables of header file within #ifndef and #endif syntax.That should solve the multiple definition error.

Your function.h should look like,

#ifndef FUNCTION_H

#define FUNCTION_H

//variables declaration and prototype declaration goes here

#endif

1 Comment

Please explain how you can type long words such as "prototypes" and "multiple definition", but you can't type a small word such as "you". I'm curious because many people do this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.