如何在忽略链接顺序的情况下链接源
How do i link sources while ignoring the linking order?
我试着重新创建几天前做的一个小测试,尽管代码与当时不同,但它的工作方式类似。我知道链接器是如何工作的,它忽略了在开始链接文件时没有使用的所有内容。所以我有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 */
看看这个。
相关文章:
- CMake-按正确顺序将项目与C运行时对象文件链接
- libavdevice 和 x11 的静态链接库应该以什么顺序链接?
- 链接库时的默认目录上的GCC或G 路径搜索顺序
- 编写链接函数的更短/更有效的方法,该函数按字典顺序添加新元素
- 双链表中按字母顺序排序的链接
- 为什么更改链接顺序可以修复一个系统上的一些链接错误?
- 链接列表并按字母顺序插入字符串
- 队列顺序中的链接列表
- AC_LANG_PROGRAM由于链接器选项的顺序失败了链接阶段
- 如何确定最快的链接顺序
- 通过Microsoft Visual Studio 2010 IDE 进行精确的库链接顺序控制
- 没有调用C++析构函数,具体取决于链接顺序
- 不同库中的相同符号和链接顺序
- 库的链接顺序问题
- 如何在忽略链接顺序的情况下链接源
- 为什么使用内联函数的程序根据链接顺序和参数具有不同的行为
- 绕过 gcc 中的静态链接顺序问题
- 在Qt Android项目中使用OpenCV时的链接顺序
- 是否可以在 cmake 中更改库链接顺序
- avcodec_alloc_context引用未定义,但ffmpeg链接顺序正确