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

标签 c static struct static-libraries

我需要向客户端提供一个 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/

相关文章:

go - 通过另一个结构字段的类型声明结构字段的类型

Java静态方法+类

php - 获取实例的静态属性

java - tomcat开发配置,如何添加webapp,以及引用静态文件

c - 执行家族

swift - 解码简单的 API 数组 Swift

c - 如何使用结构将文件的内容正确传递给 qsort?

C - malloc 分配过多内存

c - 在 Win32 中等待串口传输完成

c - DCRaw 说我应该在 gcc 中使用 -O4 进行编译。 -O4存在吗?