40

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?

Sadique
  • 22,572
  • 7
  • 65
  • 91
Manish
  • 1,985
  • 2
  • 20
  • 29

4 Answers4

45

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

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • :( I thought so. Guess I need to stop being so lazy! – Manish Mar 31 '11 at 12:08
  • @Manish:: Its better than writing the declaration in every `.c` files. And you know `Ctrl+C` -- `Ctrl+V` also works. – Sadique Mar 31 '11 at 12:14
  • +1 you can have any colour you want as long as it's black LOL – pmg Mar 31 '11 at 12:16
  • 3
    @Acme: Ctrl+C -- Ctrl+V is exactly the thing I want to avoid. I know that if I change it in one c file, I'll forget to change it in other which will lead to a debugging nightmare. – Manish Mar 31 '11 at 12:22
  • Does anyone know if there is a tool to generate the header files? – dykeag Apr 01 '20 at 15:04
18

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;
}
user812786
  • 4,302
  • 5
  • 38
  • 50
tipaye
  • 454
  • 3
  • 6
  • 1
    There is one downside to this approach. If the constant isn't used in a compilation unit, some compilers will throw a warning which cannot be silenced without resorting to compiler specifics. – Sander Mertens Oct 19 '21 at 11:49
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
pmg
  • 106,608
  • 13
  • 126
  • 198
1

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
Nekuromento
  • 2,147
  • 2
  • 16
  • 17