Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shared c constants in a header

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?

like image 998
Manish Avatar asked Mar 31 '11 12:03

Manish


People also ask

Do constants go in header files?

cpp . For this reason, constexpr variables cannot be separated into header and source file, they have to be defined in the header file. Given the above downsides, prefer defining your constants in the header file.

Can we include .C file in header?

The only files you should include in your . c files are header files that describe an interface (type definitions, function prototype declarations, macro defintions, external declarations), not an implementation.

Can we declare variable in header file?

Yes. Although this is not necessarily recommended, it can be easily accomplished with the correct set of macros and a header file. Typically, you should declare variables in C files and create extern definitions for them in header files.


2 Answers

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

like image 140
Armen Tsirunyan Avatar answered Oct 02 '22 14:10

Armen Tsirunyan


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; } 
like image 37
tipaye Avatar answered Oct 02 '22 14:10

tipaye