如何在忽略链接顺序的情况下链接源

How do i link sources while ignoring the linking order?

本文关键字:链接 顺序 情况下      更新时间:2023-10-16

我试着重新创建几天前做的一个小测试,尽管代码与当时不同,但它的工作方式类似。我知道链接器是如何工作的,它忽略了在开始链接文件时没有使用的所有内容。所以我有test.cpp、test2.cpp、test.h、test2.h和main.cpp.

test.h

#ifndef TEST_H
#define TEST_H
void Test(void);
void TestTestTest(void);
#endif /* TEST_H */

测试2.h

#ifndef TEST2_H
#define TEST2_H
void TestTest(void);
#endif /* TEST2_H */

test.cpp

#include <test.h>
#include <test2.h>
#include <iostream>
void Test(void)
{
    std::cout << "Test" << std::endl;
}
void TestTestTest(void)
{
    TestTest();
    std::cout << "TestTestTest" << std::endl;
}

test2.cpp

#include <test2.h>
#include <test.h>
#include <iostream>
void TestTest(void)
{
    Test();
    std::cout << "TestTest" << std::endl;
}

main.cpp

#include <test.h>
int main(int argc, char* argv[])
{
    TestTestTest();
    return 0;
}

链接顺序:main.otest.otest2.o

我知道,在链接Test.o时,函数Test的源代码会被忽略,但TestTestTest不会被忽略,因为main.cpp中有一个函数调用使用TestTestTest。链接test2.o时,不会忽略TestTest,因为它在函数TestTestTest中使用。但是TestTest有一个对函数Test的函数调用,以前被忽略了,所以我收到了一条错误消息。

有没有办法绕过这一点,这样订单就不会变得更疯狂,或者它会从所有的函数源中获取,并在最后删除不需要的东西?

我听说过链接器选项-fPIC,它在编译共享库时使用。但出于某种原因,当我编译除main.cpp之外的所有源代码,并将它们链接到一个共享库中,并将该库链接到main.o时,Windows说,它无法运行该应用程序,尽管它的构建没有任何问题。我不明白,为什么会发生这种事。

我使用g++构建代码。

有可能以这种方式构建源代码吗?如果有可能,我做错了什么?在构建共享图书馆时,我有什么需要记住的吗?

尝试使用属性:

__declspec(dllexport)

同时在Windows中为要使用的每个函数创建共享库。

例如test.h:

#ifndef TEST_H
#define TEST_H
void __declspec(dllexport) Test(void);
void __declspec(dllexport) TestTestTest(void);
#endif /* TEST_H */

看看这个。