c++ - 其他文件中的静态函数访问

标签 c++ c unix gcc static

static定义的函数是否有可能在文件范围之外被访问?

最佳答案

这取决于您所说的“访问”是什么意思。当然,不能在任何其他文件中按名称调用该函数,因为它是 static 在不同的文件中,但是您有一个指向它的函数指针。

$ cat f1.c
/* static */
static int number(void)
{
    return 42;
}

/* "global" pointer */
int (*pf)(void);

void initialize(void)
{
    pf = number;
}
$ cat f2.c
#include <stdio.h>

extern int (*pf)(void);
extern void initialize(void);

int main(void)
{
    initialize();
    printf("%d\n", pf());
    return 0;
}
$ gcc -ansi -pedantic -W -Wall f1.c f2.c
$ ./a.out
42

关于c++ - 其他文件中的静态函数访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2182598/

相关文章:

c++ - `select`如何同时处理多个事件?

Linux "mv"命令,创建一个新文件(没有可用文件夹时)

c++ - 在带有模板参数的模板中使用重载函数

c++ - header guards 和 pragma once

java - AttachCurrentThread 崩溃

c - realloc 2 dim 数组的段错误但输出正确?

c++ - 在头文件中使用 constexpr

c++ - 在 C++ 中建模任意树(使用迭代器)

c - 在同一个 if 测试中测试多个条件?

bash - 为多个替换优化 sed