c++cmakefilec-libraries

Using c library in c++ code with makefile


I have a C library made by cluster.h and cluster.c. I compiled that with gcc -c cluster.c.

I have to use a method of this library in the main class of a C++ project. This is the makefile i use:

abundancebin: main.o profileManager.o myHash.o myMalloc.o myStack.o myStringHash.o
    g++ -o abundancebin main.o profileManager.o myHash.o myMalloc.o myStack.o         myStringHash.o
main.o: main.cpp
    g++ -c main.cpp
profileManager.o: profileManager.cpp
    g++ -c profileManager.cpp
myHash.o: myHash.cpp
    g++ -c myHash.cpp
myMalloc.o: myMalloc.cpp
    g++ -c myMalloc.cpp
myStack.o: myStack.cpp
    g++ -c myStack.cpp
myStringHash.o: myStringHash.cpp
    g++ -c myStringHash.cpp

clean:
    -rm *.o abundancebin

I tried to import the C library in main.cpp using after other imports:

#ifdef __cplusplus
extern "C" {
#endif
#include <cluster.h>
#ifdef __cplusplus
}
#endif

but when i compile with make i have this response:

main.cpp:29:21: fatal error: cluster.h: No such file or directory #include <cluster.h> ^ compilation terminated. make: *** [main.o] Error 1

if i use "cluster.h" instead of i have this error:

main.o:main.cpp:(.text+0xf68): riferimento non definito a "kmedoids" main.o:main.cpp:(.text+0xf68): rilocazione adattata per troncamento: R_X86_64_PC32 contro il simbolo non definito "kmedoids" /usr/bin/ld: main.o: bad reloc address 0x18 in section.xdata' collect2: error: ld returned 1 exit status make: * [abundancebin] Error 1`

I also tried to copy the code part i need from C library to C++ project but the compiler reports many errors like this:

error: invalid conversion from ‘void*’ to ‘int*’ [-fpermissive] vector = malloc(nnodes*sizeof(int));

The library files are in the same folder of the project files. Can someone help? Thank you


Solution

  • If you want to add some code which is wrote in c language, you have to #include it like:

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

    which tell compiler to deal with it differently, and its not necessary to change your code to c++

    1: you add your code as: #include <cluster.h> its better to change it to: #include "cluster.h" the different is, the second one tell the compiler to first search for your header in the current directory and then in the main c++ libraries directory

    your error:

    main.cpp:29:21: fatal error: cluster.h: No such file or directory
    

    is because it can't find the header, so, if cluster.h is in the same directory as main.cpp, use #include "cluster.h" or you can use -I. (which tell its in the current directory) or -I/address to tell compiler where to look for your header

    when you correct it, you get the second error, which I believe its because of your code, and I think its because of your code in main.cpp, and do not have anything with your cluster code, I suggest, try to post your code to find out what's the problem