1

I'm trying to use a C library in a C++ program. I want to link the library libcoap.a to my program. I've already made a huge program in Qt so it can't be solved by using make instead of qmake.

As a simple example I've made the following code.

connection.h:

#include <string>
#include "coap.h"
void sendData(std::string);

connection.cpp:

#include "connection.h"
#include "coap.h"
coap_uri_t uri;

void sendData(std::string ip){
    coap_split_uri((unsigned char *)ip.c_str(), strlen(ip.c_str()), &uri );
}

main.cpp:

#include "connection.h"

using namespace std;

int main()
{
    sendData("[aaaa::c30c:0:0:2]/sen/lt");
    return 0;
}    

coaptester.pro:

TEMPLATE = app
CONFIG += console
CONFIG -= qt

unix:!macx:!symbian: LIBS += -L$$PWD/../commTest/commTest/libcoap-4.0.1/ -lcoap

INCLUDEPATH += $$PWD/../commTest/commTest/libcoap-4.0.1
DEPENDPATH += $$PWD/../commTest/commTest/libcoap-4.0.1

unix:!macx:!symbian: PRE_TARGETDEPS += $$PWD/../commTest/commTest/libcoap-4.0.1/libcoap.a

SOURCES += main.cpp \
    connection.cpp
HEADERS += \
    connection.h

I always get the same error:

undefined reference to `coap_split_uri(unsigned char*, unsigned int, coap_uri_t*)'
collect2: ld returned 1 exit status

Thanks in advance.

1 Answers1

2

Try to use (in connection.h)

extern "C" {
    #include "coap.h"
}

Besides, it is redundant to include coap.h both in connection.h and in connection.cpp (if in coap.h there are no include checks the dimension of your executable will be uselessly greater), so remove it from the .cpp.

Manlio
  • 10,768
  • 9
  • 50
  • 79
  • 1
    See excellent explanation [here](http://stackoverflow.com/questions/1041866/in-c-source-what-is-the-effect-of-extern-c) – Floris Apr 10 '13 at 12:54