简体   繁体   中英

Calling C library from C++

I have a C library written by someone else that I wish to call from my C++ program. The C header is structured like this:

#ifndef INC_MOVE_CLIENT_H
#define INC_MOVE_CLIENT_H

#ifdef __cplusplus
    extern "C" {
#endif

...

int serverConnect(const char *, const char *, MoveStateDeferred *);

...

#ifdef __cplusplus
}
#endif

#endif  // ... INC_MOVE_CLIENT_H

I'm calling serverConnect in my C++ program like so:

#include "helloworld.h"
#include "moveclient.h"

int main(int argc, const char* argv[]) {
    const char* ip = "192.168.1.2";
    const char* port = "7899";
    MoveStateDeferred* m;
    serverConnect(ip, port, m);
}

This seems correct to me according to these instructions but when I try to compile I get:

$ gcc helloworld.cpp -o helloworld.out
/tmp/ccuS93Yu.o: In function `main':
helloworld.cpp:(.text+0x3c): undefined reference to `serverConnect'
collect2: ld returned 1 exit status

moveclient.c has the implementation of serverConnect and is in the same directory as the other files. Am I using an incorrect command to compile? Is there something I need to do so that moveclient.c is compiled as well? Or is it something else unrelated to the compile commadn?

This is not a compilation issue, its a linking issue.

Assuming that moveclient.c is the only additional file you need then you have several options:

You can add the .c file to the compilation line:

g++ helloworld.cpp moveclient.c -o helloworld.out

Or you can compile the .c (and your .cpp) file to object files and link them

g++ -c helloworld.cpp
gcc -c moveclient.c
g++ helloworld.o moveclient.o -o helloworld.out

Or you can link the moveclient stuff into a library and add that library to the link. The details for creating the library will depend on your system and whether you want a shared or dynamic library. But once you have the library your build line will look like this (assuming your library is called libmoveclient.so or libmoveclient.a )

g++ helloworld.cpp -L. -lmoveclient

or if you're using the seperate compilation:

g++ -c helloworld.cpp
g++ helloworld.o -L. -lmoveclient

The compilation command is wrong.

Typically you do something like this:

gcc -c helloworld.cpp -o helloworld.o
gcc -c moveclient.c -o moveclient.o
gcc    moveclient.o helloworld.o -o helloworld.out

...this links all the objects together.

You've done everything correctly so far, but you also need to tell the linker where to find the implementation of serverConnect . If you have a moveclient.c file, then:

gcc helloworld.cpp moveclient.c -o helloworld.out

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