-1

Minimum reproducible example:

// dynamic.hpp
class Test {
private:
    static void update();
};

// dynamic.cpp
#include "dynamic.hpp"
#include <iostream>

void Test::update() {
    std::cout << "Hello World!" << std::endl;
}

If I try to build this using c++ -shared dynamic.cpp it fails:

/usr/bin/ld: /tmp/ccmTgJfw.o: warning: relocation against `_ZSt4cout@@GLIBCXX_3.4' in read-only section `.text'
/usr/bin/ld: /tmp/ccmTgJfw.o: relocation R_X86_64_PC32 against symbol `_ZSt4cout@@GLIBCXX_3.4' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: bad value

I do not have much experience with the linker and would like to understand what is going on here and why that does not work.

2
  • 4
    "recompile with -fPIC" - that's quite self-explanatory, nope? stackoverflow.com/a/57649548/4165552 - related Commented Oct 23 at 8:59
  • 2
    Side note: The function is defined in the cpp file, it's only declared in the header. In C++ declaration and definition are different things, and it's important to understand the difference. Commented Oct 23 at 9:09

1 Answer 1

0

Okay so the post should probably renamed to: what does -fPIC do.

After searching a little bit I found out that when compiling a shared library in this case you have to specify -fPIC to allow position independent code PIC

Originally this issue came up because I tried to link a static library to a dynamic library. It is therefore important to also build the static library using -fPIC

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.