0

I want to define a struct in a C header file, which contains several strings. For example, 3 files are listed below and struct fileList is defined.

#include <stdio.h>

#define FILE1 "/data/file1"
#define FILE2 "/data/file2"
#define FILE3 "/data/file3"

typedef struct fileList{
    FILE1;
    FILE2;
    FILE3;
}fileList;

int main()
{
    fileList fl;
    printf("Hello world! %s\n", fl.FILE1);

}

But when I run it, I got bellow errors. Why? And do you have better solution? Thanks!

gcc test.c 
test.c:3:15: error: expected specifier-qualifier-list before string constant
 #define FILE1 "/data/file1"
               ^
test.c:8:5: note: in expansion of macro ‘FILE1’
     FILE1;
     ^
test.c: In function ‘main’:
test.c:3:15: error: expected identifier before string constant
 #define FILE1 "/data/file1"
               ^
test.c:16:36: note: in expansion of macro ‘FILE1’
     printf("Hello world! %s\n", fl.FILE1);
1
  • 4
    Structs have fields which are variables. You are trying to put values there. Values can be given to the fields at the initialization stage. Commented Dec 11, 2018 at 16:19

2 Answers 2

1

Think of #define macros as something that get searched and replaced. If you replace the macros with their definitions you get:

typedef struct fileList{
    "/data/file1";
    "/data/file2";
    "/data/file3";
}fileList;

and

printf("Hello world! %s\n", fl."/data/file1");

Those snippets are clearly not syntactically valid.


It looks like you're trying to create a struct with three string fields. One way to do that might be:

typedef struct fileList {
    const char *file1;
    const char *file2;
    const char *file3;
} fileList;

Then if you want to create an instance of that struct and set the values of those string fields to the string literals you listed, you could write:

int main() {
    fileList fl;
    fl.file1 = "/data/file1";
    fl.file2 = "/data/file2";
    fl.file3 = "/data/file3";
    printf("Hello world! %s\n", fl.file1);
}

No need for preprocessor macros at all.

Sign up to request clarification or add additional context in comments.

3 Comments

...or simply fileList fl= {"/data/file1", "/data/file2", "/data/file3"};.
file1, file2, and file3 should probably be arrays, not pointers, yes? since AFAIK, if you give a char pointer a string literal, then the string will stay a literal and won't be manipulable.
Perhaps, yes. I didn't want to get into the ins and outs of string handling. It's a complicated subject that's tackled in great depth in many other places.
0

regarding:

typedef struct fileList{
    FILE1;
    FILE2;
    FILE3;
}fileList;

this does not result in a valid data item. Suggest:

struct fileList{
    char *FILE1;
    char *FILE2;
    char *FILE3;
};
typedef struct fileList  fileList;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.