【问题标题】:Force alle functions in shared library to be defined强制定义共享库中的所有函数
【发布时间】:2021-04-04 17:24:02
【问题描述】:

我想编写一个共享库,如果我忘记实现某些功能,我想得到一个编译器/链接器错误。

考虑以下情况:

测试.h

class Test {
    public:
    Test();
};

test.cpp

#include "test.h"

main.cpp

#include "test.h"

int main() {
    new Test();
}

如果我使用此命令gcc -c -fpic test.cpp && g++ -shared -o libtest.so -Wl,--no-undefined -Wl,--no-allow-shlib-undefined test.o 创建库,则没有错误消息,但库已损坏。有没有办法强制创建未损坏的库?

编辑:添加额外的标志,但不改变结果

【问题讨论】:

  • 那没有帮助。我将不得不编写测试实现,而不是编写函数。
  • 如果你有一些单元测试,如果你没有实现它们就会失败。这怎么没有帮助?
  • 因为我的目标是在我忘记某些东西时被记住。但是,如果我必须记住编写测试或编写实现,这对我来说并没有什么不同。
  • -Wl,--no-allow-shlib-undefined 有什么不同吗?
  • 如果您不测试您的函数,即使您确实记得实现它们,您怎么知道它们没有“损坏”(例如,错误)?

标签: c++ dll shared-libraries


【解决方案1】:

这些代码已被修改:

test.h:

class Test {
    public:
    Test();
};

test.cpp:

#include "test.h"

Test::Test(){}  // you must implement the constructor

你必须实现构造函数,如果没有,你会得到一个错误“undefined reference to `Test::Test()'”。

main.cpp:

#include <iostream>
#include "test.h"

using namespace std;

int main(void)
{
        Test* t = new Test(); // you must define a pointer

        cout << "test* was created: " << t << endl;

        delete t;
        t = nullptr;

        return 0;
}

现在所有代码都可以了。然后我们使用以下命令创建一个共享库:

g++ -shared -o test.so -fPIC test.cpp

最后,我们在引用test.so共享库的同时编译main.cpp文件,得到exe输出,通过以下命令:

g++ -g main.cpp test.so -o test.exe

【讨论】:

  • 我认为你不明白我的问题(或者我不明白你的答案),但我知道如何修复代码,但我想知道的是,我如何配置编译这样,编译器拒绝在没有实现 ctor 的情况下构建库。
猜你喜欢
  • 2011-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 2010-12-10
  • 1970-01-01
相关资源
最近更新 更多