Mazorsk
Mazorsk

Reputation: 13

combining C\C++ translation units state?

I have a main.c file which includes a guarded (#ifndef...) c header, called mydefinitions.h.

In the header i declare an extern function, lets call it CppMain, to which i then call from the main.c file.

The CppMain function is defined in cppmain.cpp file which includes the (guarded) mydefinitions.h file as an extern "C" header.

The problem i am encountering is that a certain function, INIT_Pfn, which is declared and defined in the mydefinitions.h file is being defined multiple times (compiler argues multiple definitions of said method).

to my understanding the compiler is processing cppmain.cpp as a result of the definition of the said extern CppMain function but reprocess the mydefinitions.h since it is outside the scope of main.c and therefore the guard (#ifndef...) is being reinitialized - which, to me, is totally reasonable.

The main gist of the issue is that i'm trying to implement some logic in C++ as opposed to doing it all in C, but to keep the global scope\state of the main.c program translation.

Is there any way to avoid taking out the INIT_Pfn out of the mydefinitions.h file? Any other way you might think of implementing this solution without affecting mydefinitions.h? the file also defines a global variable which has dependencies all over the source...

EDITTED (added code snippets):

mydefinitions.h:

#ifndef MyDefinitions
#define MyDefinitions

unsigned int GLOBAL_STATE = 0;
extern void CppMain();

#endif // !MyDefinitions

MyCPPFile.cpp:

#ifndef MyCPPFile
#define MyCPPFile

extern "C" {
#include "mydefinitions.h"
}

extern "C" void CppMain()
{
    // cpp code here
}
#endif // !MyCPPFile

main.c file:

#include "mydefinitions.h"

int main(int argc, char *argv[])
{
    CppMain();
}

Upvotes: 1

Views: 189

Answers (2)

Den-Jason
Den-Jason

Reputation: 2573

What's happening is that every object file compiled from source contains both the integer GLOBAL_STATE as well as a runtime initialiser for it. You only need it defined once.

In the header file, declare the variable extern:

extern unsigned int GLOBAL_STATE;

In your main C file, define it:

unsigned int GLOBAL_STATE = 0;

You don't need the #define MyCPPFile malarky in the CPP file.

Upvotes: 1

eerorika
eerorika

Reputation: 238351

If the function is written in common subset of C and C++, then you could declare the function static inline and it should work.

The variable has to be defined elsewhere or has to be static since C doesn't have inline variables.

Upvotes: 0

Related Questions