问题
I'm trying to build a Visual C++ Win32 project which uses the Eclipse Paho MQTT library - see https://eclipse.org/paho/clients/c/ The library takes the form of 2 files:
- paho-mqtt3c.lib
- paho-mqtt3c.dll
The library is originally written in C - I've tried with the precompiled binary and when compiling it myself.
In my client Visual C++ project, under the linker options, I've included the correct library path in the "Additional Library Directories" field and the paho-mqtt3c.lib file directly in the "Additional Dependencies" field. However when I try to build, the linker bins out with an error for each library function used. All errors share a similar format:
Error 2 error LNK2019: unresolved external symbol "int __cdecl MQTTClient_connect(void *,struct MQTTClient_connectOptions *)" (?MQTTClient_connect@@YAHPAXPAUMQTTClient_connectOptions@@@Z) referenced in function _main c:\Project\scrapbook\MQTT_Example\MQTT_Example\main.obj MQTT_Example
My code is as follows:
#include <MQTTClient.h>
#include <MQTTClientPersistence.h>
: : :
// Start MQTT connection
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_deliveryToken token;
// Convert CString to char*
int connectResponse;
char* szBuf = strBroker.GetBuffer(strBroker.GetLength()) ;
// Create client
MQTTClient_create(&client, szBuf, "MQTTTestClient", MQTTCLIENT_PERSISTENCE_NONE, NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
MQTTClient_setCallbacks(client, NULL, NULL, msgarrvd, NULL);
// Connect to broker
if ((connectResponse = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
// Oops.. that didn't work!
}
Does anyone have any ideas about how to solve this? (I know there are millions of LNK2019 questions but I cannot find anything that has solved my problem so far...)
回答1:
So it turns out the problem was that I was attempting to include a C library (with lots of C style declared functions) in a C++ project.
The solution is to wrap the function declarations (i.e. where the header files are included) in an extern "C" block:
extern "C"{
#include <MQTTClient.h>
#include <MQTTClientPersistence.h>
}
This tells the linker to link against C rather than C++ functions.
来源:https://stackoverflow.com/questions/27999199/lnk2019-error-when-compiling-a-visual-c-win32-project-with-eclipse-paho-mqtt