我想在多个 c 文件中共享某些 C 字符串常量。常量跨越多行以提高可读性:
const char *QUERY = "SELECT a,b,c "
"FROM table...";
执行上述操作会给 QUERY 重新定义错误。我不想使用宏,因为每行后都需要退格“\”。我可以在单独的 c 文件中定义这些,并在 h 文件中外部变量,但我觉得这样做很懒。
有没有其他方法可以在 C 中实现这一点?
我想在多个 c 文件中共享某些 C 字符串常量。常量跨越多行以提高可读性:
const char *QUERY = "SELECT a,b,c "
"FROM table...";
执行上述操作会给 QUERY 重新定义错误。我不想使用宏,因为每行后都需要退格“\”。我可以在单独的 c 文件中定义这些,并在 h 文件中外部变量,但我觉得这样做很懒。
有没有其他方法可以在 C 中实现这一点?
在某个 .c 文件中,写下你所写的内容。在适当的 .h 文件中,写入
extern const char* QUERY; //just declaration
在需要常量的任何地方包含 .h 文件
没有其他好方法:) HTH
您可以使用静态常量来实现您的效果。
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;
}
你可以简单地#define
将它们分开
#define QUERY1 "SELECT a,b,c "
#define QUERY2 "FROM table..."
然后将它们加入一个定义
#define QUERY QUERY1 QUERY2
有几种方法