Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting this error: "data definition has no type or storage class"?

#include <stdio.h>
#include <stdlib.h>

struct NODE {
    char* name;
    int val;
    struct NODE* next;
};
typedef struct NODE Node;

Node *head, *tail;
head = (Node*) malloc( sizeof( Node ) ); //line 21

And I compiling like this:

cc -g -c -o file.tab.o file.tab.c

I'm getting this error message:

file.y:21:1 warning: data definition has no type or storage class [enabled by default]
like image 272
Daivid Avatar asked Sep 19 '13 22:09

Daivid


3 Answers

It looks like the line

head = (Node*) malloc( sizeof( Node ) ); //line 21

is outside the main() function. You can't do that, because you can't execute code outside functions. The only thing you can do at global scope is declaring variables. Just move it inside the main() or any other function, and the problem should go away.

(PS: Take a look at this question on why you shouldn't type-cast malloc)

like image 93
Natan Streppel Avatar answered Nov 05 '22 11:11

Natan Streppel


Try putting the malloc and variable declarations in a main function, and delete the cast on malloc. It should look like this:

#include <stdio.h>
#include <stdlib.h>

int main(){

    struct NODE
    {
        char* name;
        int val;
        struct NODE* next;
    };

    typedef struct NODE Node;

    Node *head, *tail;
    head = malloc( sizeof(Node) ); //line 21
}
like image 1
smnh3 Avatar answered Nov 05 '22 11:11

smnh3


The problem is that you're trying to call malloc when you aren't executing inside of a function. If you wrap that inside a main function, for example:

int main(int argc, char **argv)
{
    Node *head, *tail;
    head = (Node*) malloc( sizeof( Node ) );
    /* ... do other things ... */
    return 0;
}

… it works just fine. GCC's error is a little cryptic, but the problem is basically that you're trying to initialize a variable with something that isn't a constant, which is impossible outside of a function.

like image 1
Matt Patenaude Avatar answered Nov 05 '22 09:11

Matt Patenaude