I reading this page.
I follow the answer step by step to test, alse add -fvisibility=hidden to make all symbols hidden, and then I extended the code that is in the answer.
//rectangle.h
#pragma once
#include <memory>
class Rectangle {
int width, height;
public:
void set_values (int,int);
int area();
};
std::shared_ptr<Rectangle> __attribute__((visibility("default"))) get_rectangle();
//rectangle.cpp
#include "rectangle.h"
int Rectangle::area() {return width*height;}
void Rectangle::set_values (int x, int y) {
width = x;
height = y;
}
std::shared_ptr<Rectangle> __attribute__((visibility("default"))) get_rectangle() {
return std::make_shared<Rectangle>();
}
I build librectangle.so, then I code main.cpp to link librectangle.so
//main.cpp
#include "../rectangle/rectangle.h"
int main() {
auto rectangle = get_rectangle();
rectangle->set_values(2, 3);
rectangle->area();
return 0;
}
Compilation error
undefined reference to `Rectangle::set_values(int, int)'
undefined reference to `Rectangle::area()'
But, If I change the class member function to a virtual function, it will compile correctly
//changed rectangle.h
#pragma once
#include <memory>
class Rectangle {
int width, height;
public:
virtual void set_values (int,int);
virtual int area();
};
std::shared_ptr<Rectangle> __attribute__((visibility("default"))) get_rectangle();
Use Usenm -C librectangle.so to compare the normal function class and the virtual function class. The left is the normal function class. the right is the virtual function class.
nm -C librectangle.so | grep Rectangle

nm -C librectangle.so | grep area

nm -C librectangle.so | grep set_values

both demos add -visibility=hidden, the normal functions compile incorrectly, but the virtual functions compile correctly?
nmtool to see what symbols are included in librectangle.so and what are not included. Also provide the compiler flags that you are using.uminfonmcall doesn't list exported symbols, but all symbols: stackoverflow.com/questions/34732/…