0

I have some problems to build a program using g++. The program is using a library that I have written in C called libiec60063. I want to write my new project in C++ (even if not yet familiar with C++) but I can't manage to link it correctly.

For example I have the following code in a file called main.cpp

#include <libiec60063.h>

int main() {
    Select_IEC60063_Number(125, 12);
    return 0;
}

I can compile the source correctly typing

g++ -I/home/workspace/a_CommonBinary/include -c main.cpp

If I want to link it i get some error message

g++ -L/home/workspace/a_CommonBinary_draft/lib -o main main.o -lm -liec60063
main.o: In function `main':
main.cpp:(.text+0x1b): undefined reference to `Select_IEC60063_Number(double, int)'
collect2: error: ld returned 1 exit status

If I rename the main-file to main.c I can compile and link the program correctly with the GCC-Compiler using the same parameters.

Can anybody explain where there is a difference between gcc and g++?

much
  • 47
  • 1
  • 1
  • 4
  • Are you sure this library have specified function? What is the output of `nm -D /path/to/your/libiec60063.so | grep Select_IEC60063_Number`? – keltar Mar 04 '15 at 12:31
  • 1
    Add the source(`.c` or `.cpp` file), object(`.o`) or library (`.lib` or `.so`) file that contains `Select_IEC60063_Number` function. – Mohit Jain Mar 04 '15 at 12:33
  • `nm -D /path/to/your/libiec60063.so | grep Select_IEC60063_Number` returns `00000c10 T Select_IEC60063_Number` – much Mar 04 '15 at 12:37
  • Is libiec60063 a C library or a C++ library ? in case it's a C library, perhaps they didn't guard their libiec60063.h header for use in C++ code - so you'd have to do that yourself. – nos Mar 04 '15 at 12:44

1 Answers1

1

You probably forgot to put

 #ifdef __cplusplus
 extern "C" {
 #endif

near the beginning of your libiec60063.h header file, and

 #ifdef __cplusplus
 }; // end extern "C"
 #endif

near the end of your header file, or if you don't want to change the header file:

extern "C" {
#include  <libiec60063.h>
};

in your C++ code.

See this question. You need to disable name mangling. Read about compatibility of C & C++ .

BTW, you should compile with g++ -Wall -Wextra -g and perhaps with -std=c++11 and code for C++11

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547