[英]How to disable overriding function in c programming
请检查我的示例代码。
#include <string.h>
char* strcpy(char* dest, const char* src);
int main ()
{
char str1[] = "Geeks";
char str2[] = "Quiz";
puts("str1 before memcpy ");
puts(str1);
/* Copies contents of str2 to sr1 */
strcpy (str1, str2);
puts("\nstr1 after memcpy ");
puts(str1);
return 0;
}
char* strcpy(char* dest, const char* src){
*dest = '1';
}
如何避免链接器库重写此类型。
命名您的C代码。
我用库的前缀为所有全局变量(甚至是static
变量,甚至在可执行文件中)加上前缀,这使得与libc的名称冲突不再是问题(这也简化了移动代码,合并代码或使以前的static
函数extern
)。
通常,您不能阻止链接您的库的C程序作者介入您库的功能(其程序,其规则)。 但是,如果您是Linux之类的平台上的共享库作者,则可以防止他们琐碎地基于链接器重写您的库的内部函数。 一种实现方法是使用库专用(隐藏)符号别名:
示例(依赖于非标准C扩展,并使用共享库而不是静态库):
#!/bin/sh -eu
cat > h.h<<EOF
void a(void);
void A(void);
void b(void);
EOF
cat > mylib.c <<EOF
#include <stdio.h>
#include "h.h"
void b_(void);
void a()
{
b(); //overridable
}
void A(void)
{
b_(); //non-overridable
}
void b(void)
{
puts("b");
}
__attribute((visibility("hidden"),alias("b"))) typeof(b) b_ ;
//^ the b_ hidden function (unlike a static function)
//can be used from other translation units of the same shared lib
//but not from outside
EOF
gcc -c mylib.c -fpic
gcc mylib.o -o libmylib.so -shared
cat > main.c <<EOF
#include "h.h"
#include <stdio.h>
void b(void) { puts("my b"); }
int main()
{
puts("do a"); a(); puts("===");
puts("do b"); b(); puts("===");
puts("do A"); A(); puts("===");
}
EOF
gcc main.c $PWD/libmylib.so
./a.out
输出:
do a
my b
===
do b
my b
===
do A
b
===
更多信息,例如在U. Drepper的“ 如何编写共享库”中 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.