This is the error I'm getting while linking a shared object(which I created) to my main.cpp
$ g++ -Iinclude -L`pwd`/bin -lcppops -Wl,-rpath,`pwd`/bin main.cpp -o bin/out
/usr/bin/ld: /tmp/ccXHFLyv.o: in function `main':
main.cpp:(.text+0x2e): undefined reference to `add(int, int)'
/usr/bin/ld: main.cpp:(.text+0x72): undefined reference to `mul(int, int)'
collect2: error: ld returned 1 exit status
My goal is to create a shared object from a small library of dummy ops that I've created and use that shared object in a separate file. Focus is on being able to create SO and link it successfully to a test file, but maintaining this sort of a directory structure.
My directory structure is this:-
├── bin
│ ├── libcppops.so -> libcppops.so.1.0
│ ├── libcppops.so.1 -> libcppops.so.1.0
│ └── libcppops.so.1.0
├── build
│ ├── main.o
│ ├── ops1.o
│ └── ops2.o
├── include
│ ├── add.h
│ └── mul.h
├── lib
│ ├── ops1.cpp
│ └── ops2.cpp
├── main.cpp
add.h and mul.h contain only the declaration to a function. The definition of these functions are in ops1.cpp and ops2.cpp respectively. These function do nothing but return the addition and multiplication result of the inputs.
And these are the commands I've used to create object files and the shared object.
g++ -Wall -fPIC -Iinclude -c lib/ops1.cpp -o build/ops1.o
g++ -Wall -fPIC -Iinclude -c lib/ops2.cpp -o build/ops2.o
g++ -Wall -fPIC -Iinclude -c main.cpp -o build/main.o
g++ -shared -Wl,-soname,libcppops.so.1 -o bin/libcppops.so.1.0 build/ops1.o build/ops2.o
ln -sf bin/libcppops.so.1.0 bin/libcppops.so.1
ln -sf bin/libcppops.so.1.0 bin/libcppops.so
g++ -Wall -Iinclude -L`pwd`/bin -lcppops build/main.o -o out
When adding -Wl,--verbose
to linking command I'm able to see that libcppops is successfully loaded.
One other condition which I want to follow, with respect to the goal, is to maintain this directory structure(please explain if this is the reason for error) and have the SO file in bin/ and all the object files in build/ and include files and library source in include/ and lib/ respectively. This is because I plan to also maybe create a Makefile for the same purpose and then move on to do the same with CMake, step-by-step.
ps - I have used pwd
in paths to simplify representation, but used the absolute path instead of this.
Any suggestions would be helpful
Some expected solutions which I have tried already, but did not solve the problem are:
- Add
Wl,-rpath,'pwd'/bin
and also add bin directory toLD_LIBRARY_PATH
- Add -fPIC and -fPIE interchangeably to all compile and link statement, just to see if it makes a difference
- Tried linking SO file to main.o from inside bin directory with the correct paths