【发布时间】:2016-08-06 06:03:28
【问题描述】:
我尝试重新创建几天前做的一个小测试,虽然代码与当时不同,但它的工作方式相似。我知道链接器是如何工作的,并且它忽略了在它开始链接文件时没有使用的所有内容。所以我有 test.cpp、test2.cpp、test.h、test2.h 和 main.cpp。
测试.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;
}
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.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++ 来构建我的代码。
是否可以以这种方式构建源代码,如果可以,我做错了什么?在构建共享库时,我有什么需要记住的吗?
【问题讨论】:
-
谢谢,这真的帮助了我。我不知道我可以多次使用库,我一直认为会出现错误,因为函数会被多次定义。但显然情况并非如此。