I have following file structure:
src
test_lib
interface.cpp
interface.hpp
main.cpp
File contents:
// interface.hpp
#include <string>
#include <string_view>
struct Interface {
Interface(const std::string_view &);
auto set_name(const std::string_view &) -> void;
auto get_name() const -> std::string;
private:
std::string m_name;
};
// interface.cpp
#include "interface.hpp"
Interface::Interface(const std::string_view &name) : m_name(name) {}
auto Interface::set_name(const std::string_view &name) -> void {
m_name = name;
}
auto Interface::get_name() const -> std::string { return m_name; }
I compile them as follows in from the src
folder as follows:
g++ -fPIC -std=c++23 -c test_lib/interface.cpp
ld -shared interface.o -o libinterface.so
The main file is as follows:
#include "test_lib/interface.hpp"
#include <cstdint>
#include <print>
auto main(int32_t argc, char *argv[]) -> int32_t {
Interface interface("Hello Library");
return 0;
}
I compile the main and link with shared as follows:
g++ -Wall -std=c++23 -L/path_to_src/src/test_shared_lib main.cpp -Wl,-rpath -linterface
I get following errors:
/usr/bin/ld: /tmp/ccZJeRFh.o: in function `main':
main.cpp:(.text+0x44): undefined reference to `Interface::Interface(std::basic_string_view<char, std::char_traits<char> > const&)'
collect2: error: ld returned 1 exit status
The objdump
command returns this:
objdump -T --demangle libinterface.so | grep "Interface"
0000000000003538 g DF .text 0000000000000026 Interface::set_name(std::basic_string_view<char, std::char_traits<char> > const&)
000000000000355e g DF .text 0000000000000029 Interface::get_name[abi:cxx11]() const
00000000000034e0 g DF .text 0000000000000058 Interface::Interface(std::basic_string_view<char, std::char_traits<char> > const&)
00000000000034e0 g DF .text 0000000000000058 Interface::Interface(std::basic_string_view<char, std::char_traits<char> > const&)
Please help me resolve this.