1

I want to create a .so file and let the main.cpp file can call the function where from the .so file.

And these is my files.

//aa.h
#include <stdio.h>
#include <stdlib.h>
void hello();

//hola.c
#include <stdio.h>
#include "aa.h"
void hello()
{printf("Hello world!\n");}

//main.cpp
#include "aa.h"
void hello();
int main(){hello();return 0;}

This is the step below.

Step 1 : Create .so file

$ gcc hola.c  -fPIC -shared -o libhola.so

It works

Step 2 : Linking the libhola.so to main.cpp and creating a execution file called test

$ gcc main.cpp -L. -lhola -o test

Just two Step that what I tried.

And the error says:

main.cpp:(.text+0x12): undefined reference to `hello()'
collect2: error: ld returned 1 exit status

I had been tried that move the libhola.so to /usr/lib and move the aa.h to /usr/inclued,but not work.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
葉哲昌
  • 13
  • 2
  • If i am right, header file should contain `#ifndef SOME_NAME #define SOME_NAME // Do something #endif` – Shravan40 Dec 29 '16 at 22:52
  • 1
    The C++ language mangles all function names to include the return type and the parameter types. C language does not do that. the `gcc` compiler is not for compiling/linking C++ code. Use `g++` or `gpp` instead. The get the c++ main program to handle the function `hello` in the library, the header file for the library must have `#ifdef cplusplus { .... } wrapped around the prototype for the `hello` function. Note, since the prototype for `hello` is in the header file, do not repeat that prototype in the `main.c` file – user3629249 Dec 29 '16 at 23:17
  • call `ldconfig` from cmd prompt. also check whether `ldconfig -p | grep "hola"` gives some result. – sameerkn Dec 30 '16 at 06:54

1 Answers1

2

You are compiling the shared library as a C file (specifically hello() function) but you are linking it while compiling a C++ source. You need to make sure hello() can be called (i.e. not name mangled) from a C++ executable.

i.e. Add extern "C" in your header aa.h:

#ifdef __cplusplus
 extern "C" {
#endif
void hello();

#ifdef __cplusplus
}
#endif

I'd suggest adding an include guard too.

Alternatively, if you rename main.cpp to main.c then it'd compile fine without this.

P.P
  • 117,907
  • 20
  • 175
  • 238