L
L
LittleBuster2014-11-05 06:37:07
C++ / C#
LittleBuster, 2014-11-05 06:37:07

Linking a C library to a C++ application. How?

There is a C library built like this:

gcc -fPIC -c DHT_Driver/common_dht_read.c -o DHT_Driver/common_dht_read.o -std=gnu99
gcc -fPIC -c DHT_Driver/pi_dht_read.c -o DHT_Driver/pi_dht_read.o -std=gnu99
gcc -fPIC -c DHT_Driver/pi_mmio.c -o DHT_Driver/pi_mmio.o -std=gnu99
gcc -shared DHT_Driver/common_dht_read.o DHT_Driver/pi_dht_read.o DHT_Driver/pi_mmio.o -o DHT_Driver/libdht_driver.so

Include .h file with exported function
extern int pi_dht_read(int type, int pin, float* temperature, float* humidity);

But when building a g ++ application with linking this lib, it writes an error:
g++ main.cpp -ldht_driver
/tmp/ccxRKglu.o: In function `main':
main.cpp:(.text+0x1c): undefined reference to `pi_dht_read(int, int, float*, float*)'
collect2: error : ld returned 1 exit status

And if I create a C application and compile gcc, then there are no problems.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
mamkaololosha, 2014-11-05
@LittleBuster

#ifdef __cplusplus , not #ifdef cplusplus

S
Samuel_Leonardo, 2014-11-05
@Samuel_Leonardo

Try
extern "C" int pi_dht_read(int type, int pin, float* temperature, float* humidity);

S
Sergei Borisov, 2014-11-05
@risik

Everything as suggested by @Samuel_Leonardo , but most likely you are feeding this code to the C compiler. The C compiler does not know about extern "C". C++ knows about it. Should be something like:

#ifdef cplusplus
extern "C"
#endif
int pi_dht_read(int type, int pin, float* temperature, float* humidity);

or better:
#ifdef cplusplus
extern "C" {
#endif

int pi_dht_read(int type, int pin, float* temperature, float* humidity);

#ifdef cplusplus
}
#endif

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question