shared c constants in a header

╄→尐↘猪︶ㄣ 提交于 2019-11-29 16:08:03

问题


I want to share certain C string constants across multiple c files. The constants span multiple lines for readability:

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.

Is there any other way to achieve this in C?


回答1:


In some .c file, write what you've written. In the appropriate .h file, write

extern const char* QUERY; //just declaration

Include the .h file wherever you need the constant

No other good way :) HTH




回答2:


You could use static consts, to all intents and purposes your effect will be achieved.

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);
}

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;
}



回答3:


You can simply #define them separate

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

and then join them in one definition

#define QUERY QUERY1 QUERY2



回答4:


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


来源:https://stackoverflow.com/questions/5499504/shared-c-constants-in-a-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!