Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ dll in C program

Tags:

c++

c

dll

I'd like to create a dll library from C++ code and use it in C program. I'd like to export only one function:

GLboolean load_obj (const char *filename, GLuint &object_list);

Header file from library:

#ifndef __OBJ__H__
#define __OBJ__H__

#include <windows.h>  
#include <GL/gl.h>
#include <GL/glext.h>
#include <GL/glu.h>
#include <GL/glut.h>

#if defined DLL_EXPORT
#define DECLDIR __declspec(dllexport)
#else
#define DECLDIR __declspec(dllimport)
#endif

extern "C" GLboolean load_obj (const char *filename, GLuint &object_list);

#endif // __3DS__H__

in .cpp (in library project) function is also declared as:

extern "C" GLboolean load_obj (const char *filename, GLuint &object_list)
{
 code...
}

File .lib is added in VS project options (Linker/Input/Additional dependencies). .dll is in folder where .exe is. When I compile C project - error:

Error   1   error C2059: syntax error : 'string'    

It is about part "extern "C" " in header file.

I've tried to change header file to:

extern GLboolean load_obj (const char *filename, GLuint &object_list);

then

Error   1   error C2143: syntax error : missing ')' before '&'  
Error   2   error C2143: syntax error : missing '{' before '&'  
Error   3   error C2059: syntax error : '&' 
Error   4   error C2059: syntax error : ')' 

and even when I changed & to * appeared:

Error   6   error LNK2019: unresolved external symbol _load_obj referenced in function _main    main.obj    

I've no idea why it is wrong. .lib .h and .dll are properly added.

like image 332
mmatloka Avatar asked Dec 05 '22 06:12

mmatloka


2 Answers

The parameter "GLuint &object_list" means "pass a reference to an GLuint here". C doesn't have references. Use a pointer instead.

// declaration
extern "C" GLboolean load_obj (const char *filename, GLuint *object_list);

// definition
GLboolean load_obj (const char *filename, GLuint *object_list)
{
    code...
}
like image 198
David Schmitt Avatar answered Dec 07 '22 20:12

David Schmitt


C has no references, as David pointed out.

In addition, take out extern "C". C does not have a use for nor know about it.

If you need to share the header, do something like:

#ifdef __cplusplus
    extern "C" {
#endif

/* extern "C" stuff */

#ifdef __cplusplus
    }
#endif

In C, __cplusplus won't be defined.

like image 29
GManNickG Avatar answered Dec 07 '22 18:12

GManNickG