Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing A global variable between C and C++ Files

Tags:

c++

c

scope

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!

like image 265
PumpkinPie Avatar asked Sep 13 '25 20:09

PumpkinPie


1 Answers

Your main.h should look like

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

To make sure globalvar has C linkage.

like image 88
Mohit Jain Avatar answered Sep 15 '25 09:09

Mohit Jain