简体   繁体   English

在头文件中设置常量char *?

[英]Setting a constant char* in a header file?

If I wanted to set a private, constant character array in a header file, how could you do that? 如果我想在头文件中设置一个私有的,恒定的字符数组,那怎么办? Compilers don't seem to like it.. Here is what I tried. 编译器似乎不喜欢它。这是我尝试过的。

static const char *foo = "SomeCharArray";

Use extern keyword in the following way. 通过以下方式使用extern关键字。

// myfile.h
extern const char* foo;

// myfile.cpp
const char* foo = "SomeCharArray";

The following code compiles fine: 以下代码可以正常编译:

consty.h: consty.h:

static const char *foo = "SomeCharArray";

consty.c: consty.c:

#include <stdio.h>
#include "consty.h"
int main()
{
    printf ("Hi %s\n", foo);
    return 0;
}

Note that any file that includes consty.h will get its own copy of foo. 请注意,任何包含consty.h文件consty.h将获得其自己的foo副本。 Other people have described the proper way to share global variables with extern . 其他人描述了与extern共享全局变量的正确方法。

file.h: file.h:

extern const char* foo;
#define FOO_DATA "SomeCharDATA"

file.c: file.c:

const char *foo = FOO_DATA;

Given that this: 鉴于此:

static const char *foo = "SomeCharArray";

is a perfectly valid C (even in an header file) I think you should ask yourself why you want this in an header! 是一个完全有效的C(即使在头文件中),我想您应该问自己为什么要在头文件中使用它!

If you need a variable scope to be restricted to a .c file just put the declaration in that file. 如果需要将变量范围限制为.c文件,只需将声明放入该文件中即可。 If you find yourself in need of sharing private data between two .c files, you probably have not split the functions and data in the most appropriate way across your files. 如果发现自己需要在两个.c文件之间共享私有数据,则可能未在文件中以最适当的方式拆分功能和数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM