tuc*_*cio 5 c++ linux cmake dynamic-linking
我正计划实现自己的 malloc/free,但在尝试将共享库与可执行文件链接时遇到了一些问题。
现在,我可以让它与 LD_PRELOAD 一起工作,但不能通过将 .so 链接到可执行文件,尽管我可以获得类似的库(如 tcmalloc),只需将它们链接到我的可执行文件即可正常工作,并且想要执行以下操作相同的。
我正在使用 cmake 构建所有内容,这是我的共享库的 CMakeLists:
cmake_minimum_required(VERSION 2.8)
project(allocator)
add_library(allocator SHARED exports.cpp)
target_link_libraries(allocator dl)
target_compile_features(allocator PRIVATE cxx_range_for)
Run Code Online (Sandbox Code Playgroud)
这是exports.cpp:
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stdio.h>
#include <dlfcn.h>
typedef void * (*MallocType)(size_t);
typedef void (*FreeType)(void *);
static bool g_initialized = false;
static MallocType real_malloc = nullptr;
static FreeType real_free = nullptr;
static void alloc_init(void)
{
real_malloc = (MallocType) dlsym(RTLD_NEXT, "malloc");
if (!real_malloc)
{
fprintf(stderr, "Error in `dlsym`: %s\n", dlerror());
}
real_free = (FreeType) dlsym(RTLD_NEXT, "free");
if (!real_free)
{
fprintf(stderr, "Error in `dlsym`: %s\n", dlerror());
}
g_initialized = true;
}
extern "C" void * malloc(size_t size)
{
if (!g_initialized)
{
alloc_init();
}
printf("Allocate %u.\n", size);
return real_malloc(size);
}
extern "C" void free(void *ptr)
{
if (!g_initialized)
{
alloc_init();
}
printf("Free %p.\n", ptr);
real_free(ptr);
}
Run Code Online (Sandbox Code Playgroud)
正如我所说,尝试将生成的 .so 链接到可执行文件并没有真正链接库(ldd 中没有条目,并且调用了 libc malloc)。我想知道我做错了什么。
编辑:我也尝试过编译
g++ -o liballocator.so -shared exports.cpp -std=c++11 -fPIC -ldl
g++ -o test launcher.cpp memusage.cpp app.cpp -ldl -L. -lallocator -std=c++11
Run Code Online (Sandbox Code Playgroud)
CMake 不是您选择的工具。CMake 为 C 源代码创建 makefile 或 IDE 项目文件,并有一种工作假设,即所有代码都以常规方式执行常规操作。如果您承诺提供自己的 malloc,则情况不再如此。
大多数 C 编译器通常可以通过调整链接标志的顺序来链接用户提供的 malloc 版本。但这是一个容易出错的过程,因为可能存在间接调用或提前绑定的子模块。您可以通过将 malloc() 重命名为 mymalloc() 来立即解决所有这些问题,但当然您必须重写客户端代码。
| 归档时间: |
|
| 查看次数: |
1368 次 |
| 最近记录: |