gpt4 book ai didi

c - 在静态库中隐藏结构定义

转载 作者:太空狗 更新时间:2023-10-29 17:18:47 26 4
gpt4 key购买 nike

我需要向客户端提供一个 C 静态库,并且需要能够使结构定义不可用。最重要的是,我需要能够使用全局变量在库初始化之前执行代码。

这是我的代码:

private.h


#ifndef PRIVATE_H
#define PRIVATE_H

typedef struct TEST test;

#endif


private.c (this should end up in a static library)

#include "private.h"
#include <stdio.h>

struct TEST
{
TEST()
{
printf("Execute before main and have to be unavailable to the user.\n");
}

int a; // Can be modified by the user
int b; // Can be modified by the user
int c; // Can be modified by the user

} TEST;


main.c

test t;

int main( void )
{
t.a = 0;
t.b = 0;
t.c = 0;

return 0;
}

显然这段代码不起作用...但显示我需要做什么...有人知道如何使它起作用吗?我在谷歌上搜索了很多,但找不到答案,我们将不胜感激任何帮助。

TIA!

最佳答案

如果你使用的是 gcc,你可以使用 constructor 属性,

void runs_before_main(void) __attribute__((constructor))
{
...
}

来自 gcc 文档

The constructor attribute causes the function to be called automatically be- fore execution enters main (). Similarly, the destructor attribute causes the function to be called automatically after main () has completed or exit () has been called. Functions with these attributes are useful for initializing data that will be used implicitly during the execution of the program.

You may provide an optional integer priority to control the order in which constructor and destructor functions are run. A constructor with a smaller priority number runs before a constructor with a larger priority number; the opposite relationship holds for destructors. So, if you have a constructor that allocates a resource and a destructor that deallocates the same resource, both functions typically have the same priority. The priorities for constructor and destructor functions are the same as those specified for namespace-scope C++ objects

如果您想对用户隐藏结构,请在 header 中声明该结构,但在 c 文件中定义它,传递指针。例如:

// foo.h
typedef struct private_foo foo;
foo * create_foo(void);
void free_foo(foo * f);

// foo.c
struct private_foo {
int i;
}
foo * create_foo(void){
foo * f = malloc(sizeof(*foo));
if (f) f->i = 1;
return f;
}
...

foo->i 将无法在 foo.c 之外访问。

关于c - 在静态库中隐藏结构定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2895331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com