views:

68

answers:

1

Hello there,

I have an MFC application in which I have declared a Global Object say "obj" in a file called MiRec2PC.cpp now I want to use this object in a C file.

I have used an approach in which I include the header file in which the structure of that particular object is declared. I also use a keyword "extern" with that obj when I use it . but still the compiler is showing a link error:

LINK : warning LNK4098: defaultlib "LIBCMT" conflicts with use of other libs; use /NODEFAULTLIB:library
httpApplication.obj : error LNK2001: unresolved external symbol _m_iRecordInst
Debug/MiRec2PC.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.
Creating browse info file...

MiRec2PC.exe - 2 error(s), 12 warning(s)  

Regards

Umair

+1  A: 

You cannot access classes from C++ in C without some sort of indirection and/or interface. If you really want to use it in C (Why?) then you will have to devise some kind of extern "C" interface to your object.

E.g. implement some cinterface.h:

#ifdef __cplusplus
extern "C" {
#endif

// It does not have to be void* but at this point it is the easiest thing to use.
typedef void * ObjCType;
ObjCType obj_get_obj (void);
int obj_get_value(ObjCType);

#ifdef __cplusplus
};
#endif

And then in cinterface.cpp implement the C language interface delegating to the Obj's member functions.:

#include <obj.hpp>
#include <cinterface.h>

// This is defined somewhere else.
extern Obj obj;

ObjCType obj_get_obj ()
{
  return &obj;
}

int obj_get_value(ObjCType o)
{
  return static_cast<Obj*>(o)->get_value ();
}

And finally, use the C interface in your source.c:

#include <cinterface.h>

int main ()
{
  ObjCType o = obj_get_obj ();
  int x = obj_get_value (o);
}
wilx
Note that you don't have to repeat the linkage specification for the function definitions.
Georg Fritzsche
@Georg: Ok, edited.
wilx
Could you tell me the other way round how to use C++ variable not objects in C files with out using header files !
Omayr
Oh, and there is a cast missing: `return static_cast<Obj*>(o)->get_value();`.
Georg Fritzsche
@Georg: Fixed now.
wilx
@Umair: For fundamental types you can use just plain pointers that you pass through either using extern "C" declared function or extern "C" using pointer declaration, which usually means adding it to some header anyway.
wilx