简体   繁体   中英

C++ dll using a method in a dll

I'm trying to get a simple c++ program to use a method in a dll. I've been receiving a variety of errors as I've adjusted the code and have been stuck mostly, as in the code posted below, with "undefined reference to" the method. The code below is being compiled as follows.

g++ -c testdll.cpp
g++ -shared -o testdll.dll testdll.o
g++ -o test test.cpp -L./ -ltestdll

error

g++ -o test test.cpp -L./ -ltestdll
C:\Users\ROGERF~1\AppData\Local\Temp\cca9YhFn.o:test.cpp:(.text+0x53): undefined
 reference to `__imp__ZN7TestDLL9writeDataESs'
collect2.exe: error: ld returned 1 exit status

I have no idea why directory C:\\Users\\ROGERF~1\\AppData\\Local\\Temp\\ is involved in the process. That showed up after I started using code from the Microsoft website in the header file. Previously, I was just getting undefined reference to 'writeData'

testdll.cpp

#include <stdio.h>
#include <string>
using namespace std;

class TestDLL {
public:
    string data1;

    public: void writeData (string s) {
        printf ("%s \n", s.c_str());
    }
};

TestDLL.h

#ifndef TESTDLL_H
#define TESTDLL_H

#ifdef TRADITIONALDLL_EXPORTS
#define TRADITIONALDLL_API __declspec(dllexport)
#else
#define TRADITIONALDLL_API __declspec(dllimport)
#endif

#ifdef __cplusplus
extern "C"
{
#endif

class TestDLL {
    public:
       std::string data1;

    public:
        TRADITIONALDLL_API void writeData (std::string);
};
#ifdef __cplusplus
}
#endif
#endif // TESTDLL_H

test.cpp

#include <string>
#include "TestDLL.h"
using namespace std;
class TestDLL;
int 
main () {
  TestDLL testdll;
  testdll.writeData ("success");
} 

Extended explanation: I've focused this down to something easy to post and hopefully easy for someone to answer. I was a C programmer back at the dawn of the PC era but haven't done much with C++ ever or C since then. I've been a Java programmer for quite some time (along with web stuff). Right now, I'm dealing with an existing program that can be extended with dlls, and the dlls need to be connected to a system written in Java. I've done the first step in JNI, so I have Java connected to a single dll. But the architecture needs to be:

Existing C application - dll extensions - dll for JNI - Java system

with communication both ways.

What happens if you add the two following lines to testdll.cpp:

#define TRADITIONALDLL_EXPORTS 1
#include "TestDLL.h"

I suspect that what's happening is that you're not doing that, so GCC doesn't know to compile TestDLL::writeData() with DLL export linkage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM