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

时间:2016-04-14 15:12:45

标签: c++ linker

我试图在几天前重新创建一个小测试,虽然代码与当时不同,但它的工作方式类似。我知道链接器是如何工作的,并且它忽略了在开始链接文件时未使用的所有内容。所以我有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 */

test2.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;
}

测试2.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.o test.o test2.o

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

有没有办法解决这个问题,以至于订单不是匆匆的,或者说它需要所有的功能来源,并且最后切掉,不需要什么?

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

我使用g ++来构建我的代码。

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

1 个答案:

答案 0 :(得分:0)

尝试使用属性:

__declspec(dllexport)

在Windows中创建包含您要使用的每个功能的共享库。

例如test.h:

#ifndef TEST_H
#define TEST_H

void __declspec(dllexport) Test(void);
void __declspec(dllexport) TestTestTest(void);

#endif /* TEST_H */

请参阅this

相关问题