33

我想在多个 c 文件中共享某些 C 字符串常量。常量跨越多行以提高可读性:

const char *QUERY = "SELECT a,b,c "
                    "FROM table...";

执行上述操作会给 QUERY 重新定义错误。我不想使用宏,因为每行后都需要退格“\”。我可以在单独的 c 文件中定义这些,并在 h 文件中外部变量,但我觉得这样做很懒。

有没有其他方法可以在 C 中实现这一点?

4

4 回答 4

37

在某个 .c 文件中,写下你所写的内容。在适当的 .h 文件中,写入

extern const char* QUERY; //just declaration

在需要常量的任何地方包含 .h 文件

没有其他好方法:) HTH

于 2011-03-31T12:04:06.360 回答
14

您可以使用静态常量来实现您的效果。

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:

#ifndef MYFUNC_H
#define MYFUNC_H
void myfunc(void);
#endif

myfunc.c:

#include "myext.h"
#include "myfunc.h"
#include <stdio.h>

void myfunc(void)
{
    printf("%d\t%lu\t%f\n", myx, myy, myz);
}

我的ext.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;
}
于 2015-02-17T17:21:22.620 回答
3

你可以简单地#define将它们分开

#define QUERY1 "SELECT a,b,c "
#define QUERY2 "FROM table..."

然后将它们加入一个定义

#define QUERY QUERY1 QUERY2
于 2011-03-31T12:05:56.307 回答
0

有几种方法

  • 将变量放在一个文件中,在头文件中声明它们外部并在需要的地方包含该头文件
  • 考虑使用一些外部工具在宏定义的末尾附加“\”
  • 克服你的懒惰并在所有文件中将变量声明为 extern
于 2011-03-31T12:12:29.013 回答