PumpkinPie
PumpkinPie

Reputation: 169

Sharing A global variable between C and C++ Files

I have two files. One is a C file the other is a C++ file.

in main.C

char globalvar = 0;

int main()
{
     .....
}

in main.h

extern char globalvar;

in file2.cpp

#include "main.h"

int function()
{
    globalvar = 5;  //ERROR, globalvar is undefined.
    ...

}

So basically I have a project that is part C and part C++. I have a global variable declared in main.c I have been successfully able to access this global in all of the C files, but the C++ files do not recognize it.

Does anyone have any thoughts on what is going on?

Any help would be appreciated!

Upvotes: 4

Views: 3116

Answers (1)

Mohit Jain
Mohit Jain

Reputation: 30489

Your main.h should look like

#ifdef __cplusplus
extern "C" {
#endif
extern char globalvar;
#ifdef __cplusplus
}
#endif

To make sure globalvar has C linkage.

Upvotes: 10

Related Questions