Question

I have developped a dll in C and I have called in my C++ program with this method

#include <cstdlib>
#include <iostream>
#include <windows.h>

#ifdef __cplusplus
extern "C" {
#endif
#include "mydll.h"
#ifdef __cplusplus
}
#endif
using namespace std;

int main(int argc, char *argv[])
{
    struct myown_struct *ss = NULL;
    int i = 0,j = 0, result = 0;
    struct myown_struct2 *s = NULL;
    myfunction("string1", "string2", "string3", 1500);
    system("PAUSE");
    return EXIT_SUCCESS;
}

mydll.h :

#ifndef _DLL_H_
#define _DLL_H_

#if BUILDING_DLL
# define DLLIMPORT __declspec (dllexport)
#else /* Not BUILDING_DLL */
# define DLLIMPORT __declspec (dllimport)
#endif /* Not BUILDING_DLL */

struct myown_struct {
  int fd;
  char buf[32];
  unsigned int len;
} __attribute__((packed));

DLLIMPORT void myfunction(char *s1, char* s2, char *s3, int n);

#endif /* _DLL_H_ */

I get this error :

C:\Users\user01\Desktop\test\main.cpp In function int main(int, char**) C:\Users\user01\Desktop\test\main.cpp myfunction' undeclared (first use this function)

How can I fix it?

Was it helpful?

Solution

Your header file mydll.h appears to be missing the declaration of myfunction. Correct that omission and your code will compile.

On top of that you will need to ensure that:

  • The .lib import library that was created when you compiled the DLL is passed to the linker when you link your C++ program.
  • The DLL can be found when you attempt to run your program. That is best achieved by placing the DLL in the same directory as the executable.

I would also comment that I would expect to see the extern "C" in the header file rather than forcing every single user of the header file to write extern "C". The header file really should stand alone.

OTHER TIPS

Since you are using VC++, you can use already existing API's for the same

typedef void (*myfunction)(char *buf1, char *buf2,char *buf3,char *buf4);
HMODULE hModule = LoadLibrary(_T("mydll.dll"));
if(hModule!=NULL)
    myfunction GetMyFunction = (myfunction) GetProcAddress(hModule,"myfunction");

Now use GetMyFunction()

Hope this will help

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top