OOP rules for global objects

Hi,

What I do in my current project:

1- I've developed a library by using C++ (compiler: arm-none-eabi-g++ -std=c++17) and generated a static library (arm-none-eabi-ar) with some c-api wrapper functions. In the static library there are some global instances of some classes, and exposed c functions provide access to their functionality

2- I've developed the app (compiler: arm-none-eabi-gcc) to be run on an ARM chip and linked with the static library. In the main function, a call is made to an init function which is in the static library

My observation is that, if I am not wrong, OOP inheritance rules don't work on those global objects. If I take a global object into a member function as a local variable, then I can access it via a pointer of its base class. A sample code is below:

Some test classes:

class CtBase
{
public:
    virtual void foo(void) = 0;
    int i = 0;
};

class CtDer : public CtBase
{
public:
    void foo(void) override;
};

void CtDer::foo(void)
{
    ++this->i;
}

 

Use them in a class member function implementation, where its instance (PlatformDevice) is a global object in the static library:

Version 1 - Doesn't work

CtDer der;

namespace mevoo::loni6
{

    void PlatformDevice::init(UdpComm *udp, BufferBase *b)
    {
        CtBase *ctptr = &der;

        ctptr->foo(); // doesn't work
// some more code

Version 2 - works:

namespace mevoo::loni6
{

    void PlatformDevice::init(UdpComm *udp, BufferBase *b)
    {
        CtDer der; // now a local var
        CtBase *ctptr = &der;

        ctptr->foo(); // works

// some more code

Any comment would be highly appreciated. 

Best regards,

Ozan

Parents
  • Mixing C++ and C is a little trickier than you've accounted for.   Using the C linker to combine the whole thing can easily fail to handle C++ initialization mechanisms correctly.  It's therefore usually better to use the C++ linker to link such chimeras.

Reply
  • Mixing C++ and C is a little trickier than you've accounted for.   Using the C linker to combine the whole thing can easily fail to handle C++ initialization mechanisms correctly.  It's therefore usually better to use the C++ linker to link such chimeras.

Children
More questions in this forum