1
votes

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!

2
could you show some codejuergen d

2 Answers

4
votes

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;
0
votes

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