提问者:小点点

类在C++库和程序中具有相同的接口。Exe版本是


我有一个静态库,它有一个类条,在C++库和程序的头文件中定义了相同的接口。exe的bar.cpp源代码略有不同,并且创建的对象具有不同的值。请参见下面的代码。

静态库文件。(lib_projectfoo_lib)

lib_projectfoo_lib.h

class Foo
{
public:
    int printBarA() const;
};

lib_projectfoo_lib.cpp

#include <iostream>
#include "Foo_lib.h"
#include "Bar.h"

int Foo::printBarA() const
{
    Bar bar;
    std::cout << "bar.getA() : " << bar.getA() << std::endl;
    return 0;
}

lib_projectbar.h

// Lib Bar definition
class Bar
{
public:
    Bar();
    int getA() const;
private: 
    int a;
};

lib_projectbar.cpp

#include "Bar.h"

Bar::Bar() : a(99) {}  // Different value here
int Bar::getA() const { return a; }

主程序exe代码(SARED_CLASS)

Bar.H

// exe Bar definition
class Bar
{
public:
    Bar();
    int getA() const;
private:
    int a;
};

bar.cpp

#include "Bar.h"

Bar::Bar() : a(66) { }  // Different value here
int Bar::getA() const { return a; }

main.cpp

#include "Lib_project\Foo_lib.h"

int main(int argc, char** argv)
{
    Foo foo;
    foo.printBarA();
    return 0;
}

编译后,程序的输出如下所示。Foo_lib方法foo::printbara()创建main.exe Bar.cpp中定义的Bar对象,a=66;而不是在lib bar.cpp中定义的a=99;

D:\shared_class>Release\shared_class.exe
bar.getA() : 66

在windows上编译为DLL修复了它,但是在linux上作为共享库仍然会出现这个问题,所以我需要一个与平台无关的修复。

所以我的问题是:

    <将所有库文件LI包装在命名空间中?还是改名类?我有很多实际案子的档案。是否有任何链接器或编译器选项可以工作?/li>

谢谢

分辨率:

我必须将每个类包装在一个名称空间中,以避免任何冲突。现在一切都按预期进行。


共1个答案

匿名用户

如果同一个类(code::bar/code>)在同一个程序中具有两个略有不同的定义,则违反了one definition rule(ODR)。您的程序的行为是完全未定义的。

要解决这个问题,您必须重命名的一个定义,要么更改实际名称,要么将其放在命名空间中。

(至于为什么会发生这种情况的技术细节,这是由于链接器使用静态库来解析依赖关系的方式。但由于它是UB,所以你不能依赖它。)

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(类|c++|库|程序|中|接口|exe|版|本是)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?