gpt4 book ai didi

c - 如何使常量仅对特定源文件可见,在 C 中?

转载 作者:太空宇宙 更新时间:2023-11-04 07:44:17 25 4
gpt4 key购买 nike

我想在文件中声明常量,然后在来自特定源文件的函数调用中使用它们。这些常量不能对所有文件可见。这在 C 中如何实现?

这个问题的解决方案是否依赖于编译器和IDE?

最佳答案

I want to declare constants in a file and then use them in function calls from specific source files. These constants must not be visible to all files.

通常的做法是在 .h 文件中定义常量,然后在需要了解这些常量的源文件中包含该 .h 文件。例如:

// constants.h
#define CONSTVAL1 1
#define CONSTVAL2 2
#define CONSTVAL3 3
#define CONSTVAL4 "a string"

和一个源文件:

// mysource.c
#include "constants.h"

现在你可以调用这个函数了

myfunc(CONSTVAL1);

(我不会展示使用 include guards 的高级示例。在 google 或 stack exchange 上搜索“include guards”)

关于c - 如何使常量仅对特定源文件可见,在 C 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58167128/

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