C语言 标题中的共享 c 常量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5499504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
shared c constants in a header
提问by Manish
I want to share certain C string constants across multiple c files. The constants span multiple lines for readability:
我想在多个 c 文件中共享某些 C 字符串常量。为了便于阅读,常量跨越多行:
const char *QUERY = "SELECT a,b,c "
"FROM table...";
Doing above gives redefinition error for QUERY. I don't want to use macro as backspace '\' will be required after every line. I could define these in separate c file and extern the variables in h file but I feel lazy to do that.
执行上述操作会导致 QUERY 重新定义错误。我不想使用宏,因为在每一行之后都需要退格 '\'。我可以在单独的 c 文件中定义这些并在 h 文件中 extern 变量,但我觉得这样做很懒惰。
Is there any other way to achieve this in C?
有没有其他方法可以在 C 中实现这一点?
回答by Armen Tsirunyan
In some .c file, write what you've written. In the appropriate .h file, write
在一些 .c 文件中,写下您所写的内容。在相应的 .h 文件中,写入
extern const char* QUERY; //just declaration
Include the .h file wherever you need the constant
在需要常量的地方包含 .h 文件
No other good way :) HTH
没有其他好方法:) HTH
回答by tipaye
You could use static consts, to all intents and purposes your effect will be achieved.
您可以使用静态常量,所有意图和目的都将实现您的效果。
myext.h:
myext.h:
#ifndef _MYEXT_H
#define _MYEXT_H
static const int myx = 245;
static const unsigned long int myy = 45678;
static const double myz = 3.14;
#endif
myfunc.h:
myfunc.h:
#ifndef MYFUNC_H
#define MYFUNC_H
void myfunc(void);
#endif
myfunc.c:
myfunc.c:
#include "myext.h"
#include "myfunc.h"
#include <stdio.h>
void myfunc(void)
{
printf("%d\t%lu\t%f\n", myx, myy, myz);
}
myext.c:
myext.c:
#include "myext.h"
#include "myfunc.h"
#include <stdio.h>
int main()
{
printf("%d\t%lu\t%f\n", myx, myy, myz);
myfunc();
return 0;
}
回答by pmg
You can simply #definethem separate
你可以简单地将#define它们分开
#define QUERY1 "SELECT a,b,c "
#define QUERY2 "FROM table..."
and then join them in one definition
然后将它们加入一个定义中
#define QUERY QUERY1 QUERY2
回答by Nekuromento
There are several ways
有几种方式
- place your variables in one file, declare them extern in the header and include that header where needed
- consider using some external tool to append '\' at the end of your macro definition
- overcome your laziness and declare your variables as extern in all your files
- 将变量放在一个文件中,在头文件中将它们声明为 extern 并在需要的地方包含该头文件
- 考虑使用一些外部工具在宏定义的末尾附加 '\'
- 克服你的懒惰并在所有文件中将变量声明为 extern

