Error expected specifier qualifier list before static

Во-первых, из этого: static struct foo1 { //private struct, just for this file int a; }; int main (void) { struct foo1 a = {10}; return 0; } вопрос № 1 Я получу предупреждение: warning: useless storage class specifier in empty declaration }; Что это значит? Почему static «бесполезн....

Во-первых, из этого:

static struct foo1 { //private struct, just for this file
    int a;
};

int main (void) {
    struct foo1 a = {10};
    return 0;
}

вопрос № 1

Я получу предупреждение:

warning: useless storage class specifier in empty declaration
 };

Что это значит? Почему static «бесполезный спецификатор класса хранения»? В другом контексте (статическая локальная переменная в функции или глобальная статическая, которую я хотел применить для структуры foo1, это сработало бы).

вопрос № 2

#include <stdbool.h>
static struct s_t{ //private struct (for this file only) 
    static bool is_there = false; // defaul (pre-defined) value for all instances
    int value;
};

int main (void) {}

Почему невозможно иметь статическое предопределенное значение для всех переменных типа struct s_t в c? Я просто хотел смоделировать ту же функциональность, что и в функции static local var -> сохранить значение для нескольких вызовов, в этом смысле я хотел иметь один член (bool is_there в данном случае ), которые сохраняют значение для каждой переменной типа struct foo1 (ее экземпляра). Так почему это невозможно?

вопрос № 3

Кроме того, кто-то может объяснить ошибку (в более общем смысле) из нее:

error: expected specifier-qualifier-list before ‘static’

РЕДАКТИРОВАТЬ: из комментариев я не очень понимаю концепцию класса хранилища, я знаю только из asm, существует data/text/bss segments, значит ли это, что static var имеет адрес в read-only части памяти? Или как понятие storage class в c связано с asm?

4 ответа

Лучший ответ

  1. Потому что static struct foo1 { ... это просто определение структуры, а не переменная. Вы должны добавить static при объявлении экземпляра структуры. Я предпочитаю этот стиль:

    typedef struct  { 
        int a;
    }foo_t;
    
    static foo_t a = {10};
    
  2. Потому что в C просто нет статических переменных-членов, как в C ++. В Си довольно бесполезно добавлять спецификаторы хранения или типа к одному члену структуры. Поместите его в выделенные переменные.

  3. TL; DR просто не имеет никакого смысла в вашем синтаксисе, так как у вас там нет static. Если вы не очень заинтересованы в грамматике языка, в этом нет ничего другого.

    static является спецификатором класса хранилища , const и т. Д. Являются определителями типа , а int и т. Д. Являются спецификатором типа . Термин список спецификаторов-спецификаторов происходит от формальной C-грамматики структур, которую не очень интересно читать, если вы не создаете компилятор. При объявлении члена структуры у вас есть два варианта (C17 6.7.2.1):

    specifier-qualifier-list:
       type-specifier specifier-qualifier-list(opt)
       type-qualifier specifier-qualifier-list(opt)
    

    static не соответствует ни одному из них, поскольку является спецификатором класса хранилища, поэтому компилятор говорит: «Что! Это не список спецификаторов-спецификаторов, где я ожидал найти такой, где он?»

    (И да, это рекурсивно, поэтому у вас может быть несколько из спецификатора типа или спецификатора типа, например const long const const int value;. Потому что C означает Crazy.)


3

Lundin
27 Май 2020 в 15:26

Поскольку структура похожа на тип или объект, когда вы объявляете статический член в C, это будет выглядеть так:

static int a = 0;

В этом случае «int» похож на объявленный вами тип структуры, поэтому, если вы хотите создать элемент struct static, просто сделайте так:

static s_t a;


2

min20120907
27 Май 2020 в 15:13

Ну, вполне очевидно, что вы получите предупреждение. Причина проста! Вы пытаетесь назначить класс хранилища для определения struct . Однако классы хранения применимы к объявлениям переменных. Таким образом, вы получаете приглашение. Если вы все еще хотите использовать класс хранения static, то вы можете сделать это с любой переменной, предпочтительно с любым экземпляром структуры.


0

Devansh Agarwal
27 Май 2020 в 17:51

static struct foo1 { //private struct, just for this file
        int a;
    };

Спецификатор объявления static применяется только к объявлениям объектов или функций, но не к определениям типов. Все, что вы делаете в этом утверждении, это создание типа struct foo1. Вы написали что-то вроде

static struct foo1 {
  int a;
} foo;

Тогда объект foo будет объявлен static.

Если вы объявите тип в файле .c, он будет виден только в этом файле .c. Единственный способ сделать тип видимым для нескольких файлов .c — это объявить его в заголовке и #include заголовке в каждом файле, который нуждается в нем.

Почему невозможно иметь статическое предопределенное значение для всех переменных типа struct s_t в c?

Поскольку типы C struct просто не так сложны — они просто способ определить элемент данных с несколькими атрибутами. Язык не предоставляет никакого способа иметь члены, которые являются общими для всех экземпляров типа.

Помните, что C является продуктом начала 1970-х годов и изначально разрабатывался для реализации операционной системы Unix — он был разработан, чтобы быть маленьким, переносимым и быстрым. За последние 40 с лишним лет к нему было добавлено многое, но ничего, что действительно меняет основную философию языка.


2

John Bode
27 Май 2020 в 15:33

Using CB 13.12, mingw32-gcc version 4.7.1 on win8.1 & winXP.  Simple C program that use to compile clean with CB how compiles with 1 «error: expected specifier-qualifier-list before ‘static’ «.  The line it references is «static  short sp2func».  If I remove the static qualifier then msg changes to «error: expected…before ‘main’ «.  I have never gotten this error before and I did find where other have but their solutions didn’t work for my situation.  I don’t understand the msg, but it appears to have to do with order of structs.  Checked the order of what few typedef structs are used and all declarations of the structs using typedefs come after the typedef definitions.  Thanks!

PS — neither CB nor mingw were updated from when the programs compiled clean

BTW, the build log wasn’t attached because it only contained one line, the above error msg.  So my text contained everything.  The real question was the meaning of the error msg, not a review of my code.  Having it would not have revealed the cause of the problem.

Resolution — still not sure exactly what the error msg means other than what I derived from the context of other posts on the internet.  Anyway, I resolved the problem in that the header file «included» immediately before the line of code referenced in the error, i.e. «static short sp2func», contained some extraneous text I hadn’t noticed that was entered by the tool that generated the header file.

« Last Edit: June 16, 2015, 10:14:54 pm by dseverns »


Logged

Tinku


  • #1

look at this code …. i am quite confuse why i am getting error while
compiling it by gcc.

#include <stdio.h>
struct myStructure
{
int i;
static int si;
};

int main()
{
struct myStructure a;
printf(«%u n», sizeof(a));
printf(«%u n», sizeof(struct myStructure));
return 0;
}

[email protected]$ gcc -Wall -Wextra -pedantic -ansi
static_inside_struct.c
error: expected specifier-qualifier-list before ‘static’

I dont understand why the error is coming while compiling it
cant we take static variable in structure or what ?
am i wrong some where?
if i remove static from the struct myStructure it works, but it is not
working with static variable

as we know static variable is stored somewhere else (in Data segment)
and auto variable is stored in stack (auto storage) , this is because
the error is coming ?

please teach me what exactly is being happened .
Thanks .

Advertisements

saurabh


  • #2

look at this code …. i am quite confuse why i am getting error while
compiling it by gcc.

#include <stdio.h>
struct myStructure
{
    int i;
    static int si;

};

int main()
{
    struct myStructure a;
    printf(«%u n», sizeof(a));
    printf(«%u n», sizeof(struct myStructure));
    return 0;

}

[email protected]$ gcc -Wall -Wextra -pedantic -ansi
static_inside_struct.c
error: expected specifier-qualifier-list before ‘static’

I dont  understand why the error is coming while compiling it
cant we take static variable in structure or what ?
am i wrong some where?
if i remove static from the struct myStructure it works, but it is not
working with static variable

as we know static variable is stored somewhere else (in Data segment)
and auto variable is stored in stack (auto storage) , this is because
the error is coming ?

please teach me what exactly is being happened .
Thanks .

I don’t know If this is a proper plce to ask but still ,in addition to
what OP has asked,
I tried same programm with C++(g++) and it compiles with no problems.
So is it because ‘static’ means different things in C and C++ ?

saurabh


  • #3

Static doesn’t have any sense when applied to a struct member. Either you
apply static to the whole struct, or you don’t at all.- Hide quoted text —

— Show quoted text —

Thats what the point is.
If a static member is allowed in a C++ struct,why doesnt’t it have any
sense in a C struct?

saurabh


  • #4

In

saurabh wrote:

C and C++ are different languages. To give you another example, C++
allows function definitions within structs. C doesn’t.

C is under no obligation to codify C++ constructs.


Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. [email protected]
«Usenet is a strange place» — dmr 29 July 1999
Sig line vacant — apply within

Richard,

I am sorry If I sounded like doing a comparison of C and C++ here.
I understand that languages are tools and every tool has a place where
it fits.
My intention was not to compare features of C++ and C,what I mean to
say was,
«As having a static member variable in a c++ class means that it is
common to all
objects of that class,I assumed something like, A static member inside
a struct will
be common to all instances of that struct.»
But it seems It is a wrong assumption.Just to clear my understanding
of C semantics I would
like to know why is this not possible?

Michael Schumacher


  • #5

Pietro said:

Static doesn’t have any sense when applied to a struct member.

That’s true.

Either you
apply static to the whole struct, or you don’t at all.

But what’s the point in applying «static» to a type definition?
Aren’t user-defined types automatically tied to the compilation
unit they’re defined in? I think they are, actually.

mike

Nick Keighley


  • #6

don’t quote .sigs (the bit after the «— «)

I am sorry If I sounded like doing a comparison of C and C++ here.

yoe are :)

I understand that languages are tools and every tool has a place where
it fits.

I’m not sure about this. I own a wooden butter knife.

My intention was not to compare features of C++ and C,what I mean to
say was, «As having a static member variable in a c++ class means that it is
common to all objects of that class,I assumed something like, A static
member inside a struct will be common to all instances of that struct.»
But it seems It is a wrong assumption.Just to clear my understanding
of C semantics I would like to know why is this not possible?

This is a bit of an «ask Dennis Richie» question (he designed the C
language). But we can speculate a bit. A C struct is simply a way of
defining a type which is a collection of other simpler types. Although
you can assign one instance to another they have little or no other
group semantics. So you pass a struct by value to a function and
return one by value you cannot compare structs. C structs are not
quite first-class objects. This is consistent with C’s close-to-the-
machine philosophy and what-you-see-is-what-you-get. C statements
usually compile into a small number of machine instructions there is
little going on beneath the surface. In fact struct assignment could
be said to getting very close to bending this principle. I suppose no
one thought of having data that was «global» to all structs of the
same type.

When Bjarne Stroustrup invented C++ he started with C then stretched
the semantics of various constructs, particularly the humble struct,
to thinks he wanted to do. he wanted embedded methods (functions) and
virtual methods and in the end static data. C saw no need to extend
the C language by adding these things. An although I programmed in
both C (quite a lot) and C++ (much less) I’ve never missed struct
static data from C.

Assuming just because C++ can do something therefore C can do it was
always a bad idea and much more of a bad idea now that C is a large
mature language.

Advertisements

arnuld


  • #7

Static doesn’t have any sense when applied to a struct member. Either
you apply static to the whole struct, or you don’t at all.

H&S 5, section 4.3:

static:

may appear on declarations of functions and variables.
On function definitions, it is used only to specify that the function
name is not exported to the linker. On function declarations, it
indicates that the declared function will be defined — with storage
class /static/ — later in the file. On Data Declarations, it always
signifies a defining declaration that is not exported to the linker.
Variables declared with this storage class have static extent (as opposed
to local extent, signified by /auto/ )

So, a member of a struct can not be treated as a variable according to
this definition of static. or do I need to say that static applies only
to independent variables and in OP’s case it ain’t so ?

arnuld


  • #8

Read what you said.

«what I mean to say was: As having a static member variable in a c+
+ class means that it is common to all objects of that class,I assumed
something like, A static member inside a struct will be common to all
instances of that struct.»

«But it seems It is a wrong assumption.Just to clear my
understanding of C semantics I would like to know why is this not
possible?»

I don’t think its possible to use a word like /instance/ in C
language. Anyone ?

Ben Bacarisse


  • #9

Please don’t quote sigs blocks. Snip them along with anything else
that you don’t want to comment on.

I am sorry If I sounded like doing a comparison of C and C++ here.
I understand that languages are tools and every tool has a place
where it fits.

My intention was not to compare features of C++ and C,what I mean to
say was, «As having a static member variable in a c++ class means
that it is common to all objects of that class,I assumed something
like, A static member inside a struct will be common to all
instances of that struct.»

But it seems It is a wrong assumption.Just to clear my understanding
of C semantics I would like to know why is this not possible?

[I’ve reformatted the above.]

«Why» questions can have lots of answers: sociological, historical,
technical. The most useful ones here are usually technical. There is
no technical reason for C not to have the construct you are talking
about, but what would it mean? Essentially, it would be a static
object with a qualified name. I.e.:

struct vector {
static int projection;
double c1, c2, c3;
} v;

Is very similar to:

struct vector {
double c1, c2, c3;
} v;

static int vector_projection;

so there would be little to be gained. Even when accessing the member
through a pointer, the type rules of C mean you can always tell, just
be looking at the pointer types, exactly which variable is begin
referenced. In C++, this is not true anymore and the mechanism is
therefore more interesting.

What is more, the static member would be less accessible than the
static variable unless other mechanisms were added to C. In my first
example, «projection» is only accessible through an object of type
struct vector whereas vector_projection is accessible even when no
objects of type struct vector exist.

Seebs


  • #10

If a static member is allowed in a C++ struct,why doesnt’t it have any
sense in a C struct?

Because C and C++ are different languages.

-s

Seebs


  • #11

I am sorry If I sounded like doing a comparison of C and C++ here.

No one’s complaining about a hypothetical comparison, merely pointing
out that the languages are different.

«As having a static member variable in a c++ class means that it is
common to all
objects of that class,I assumed something like, A static member inside
a struct will
be common to all instances of that struct.»
But it seems It is a wrong assumption.Just to clear my understanding
of C semantics I would
like to know why is this not possible?

Because it’s not possible.

I mean, seriously. That’s it. No one designed such a feature for C, so
there’s no such feature, so it’s not possible. It could have been, just
as we could have added a rule that declaring a struct member with the word
«coffee» in front of it caused the compiler to serve you a cup of high-quality
espresso.

But in the language which actually exists, there’s no such thing.

If you want to get to the more theoretical question of why there wouldn’t
be, it’s because C is a lower-level language, and the type has no existence
separate from the objects, so there’s noplace to put the hypothetical static
member; the things declared in a struct actually occur in each struct object,
in order, and there’s no storage space shared among all structs of the same
type. In C++, the type really has independent existence, so it makes sense
to have an object associated with the type to hold the «shared» values.

I will go so far as to grant that, given the huge amount of overloading
that the word «static» normally takes, this one makes as much sense as any
of them.

-s

Advertisements

James Kuyper


  • #12

No, we cannot. A «struct-declaration» (6.7.2.1p1), the part of the
grammar that describes members of structures, differs from the more
general «declaration» (6.7p1) in that it cannot include a storage class
specifier.

….

I tried same programm with C++(g++) and it compiles with no problems.
So is it because ‘static’ means different things in C and C++ ?

Yes, of course; they are different languages, and some of the biggest
differences are associated with the declaration of structure types (or
classes, as they are called in C++). The above declaration is
well-defined in C++, with a meaning that myStructure::si is the name of
a static int object, whose storage location is completely independent of
the location of any actual myStructure object; a simple ‘si’ may be used
to refer to that object in any member function. Since neither the ::
operator nor member functions are part of C, that would be completely
meaningless in C.

Also, keep in mind that static means many different things just in C
alone, never mind comparing the two language: it can indicate internal
linkage, or static storage duration, or (when it appears inside the
leading dimension of the declaration of an array parameter in C99) a
minimum requirement on the length of the corresponding array argument.

James Kuyper


  • #13

saurabh wrote:
….

Richard,

I am sorry If I sounded like doing a comparison of C and C++ here.

You sounded like you were doing that, because you were doing it. You’re
asking why a C++ features is not supported by C; that is, in principle,
no different from asking why a given Fortran feature is not supported by
C. They are different languages, and forgetting that fact can only lead
to trouble.

I understand that languages are tools and every tool has a place where
it fits.
My intention was not to compare features of C++ and C,what I mean to
say was,
«As having a static member variable in a c++ class means that it is
common to all
objects of that class,I assumed something like, A static member inside
a struct will
be common to all instances of that struct.»

That’s not a very good description. It could easily be read as implying
that the following code:

myStructure ms;
ms.si = 5;

was legal. The correct code would be myStructure::si = 5;

But it seems It is a wrong assumption.Just to clear my understanding
of C semantics I would
like to know why is this not possible?

It is possible, or C++ could not have done it. It is not supported by C
as a matter of choice, not because it couldn’t be done. It is an
innovation introduced in C++. Unlike some other C++ innovations such as
‘const’ and ‘inline’, the committee has not (yet) chosen to move this
one back into C.

This is probably because the scope of struct member names is different
in C from the class scope that they have in C++. In C++, class scope is
meaningful only in class member functions — which C does not have. You
can access such members from outside of such functions only by the use
of the :: operator, which C does not have and does not need. If we
remove those restriction to allow a C static member variable, then it
would be indistinguishable from an ordinary static non-member variable,
which is something C already allows.

Keith Thompson


  • #14

Michael Schumacher said:

Pietro Cerutti wrote: […]

Static doesn’t have any sense when applied to a struct member.

That’s true.

Either you
apply static to the whole struct, or you don’t at all.

But what’s the point in applying «static» to a type definition?
Aren’t user-defined types automatically tied to the compilation
unit they’re defined in? I think they are, actually.

You don’t apply «static» to a type; you apply it to an object.

For example:

struct foo {
int x;
int y;
};
static struct foo this_is_a_static_object;

arnuld


  • #15

I have no problem using the word «instance» in C — as in, for example,
«an object is an instance of a type».

Yes, an object is an instance of type as long as the type is Class which
is an OO thingy. I use the word object for an instance of a Class. K&R2
use it for «anything which occupies memory». So I guess you use it in
sense of K&R2 by that means:

int i = 0;

i is an instance of int. I feel good with «i is a variable of type int».

Keith Thompson


  • #16

arnuld said:

Yes, an object is an instance of type as long as the type is Class which
is an OO thingy. I use the word object for an instance of a Class.

C, of course, doesn’t have classes.

K&R2
use it for «anything which occupies memory».

Does K&R2 actually use those exact words?

So I guess you use it in
sense of K&R2 by that means:

int i = 0;

i is an instance of int. I feel good with «i is a variable of type int».

Certainly «i is a variable of type int», or «i is an object of type
int», is correct. The issue is whether referring to i as an
«instance» of type int is also correct. I’d say it is, though I
probably wouldn’t use that word.

<OT>I’m not sure that the C++ standard used the word «instance»
with any special technical meaning either. I do know that its
definition of the word «object» is very similar to C’s, and is not
limited to objects of class type.</OT>

Advertisements

arnuld


  • #17

Does K&R2 actually use those exact words?

Can’t remember. I have a hard-copy and tried finding it where I read bt
was unsuccessful.

Certainly «i is a variable of type int», or «i is an object of type
int», is correct. The issue is whether referring to i as an «instance»
of type int is also correct. I’d say it is, though I probably wouldn’t
use that word.

<OT>I’m not sure that the C++ standard used the word «instance» with any
special technical meaning either. I do know that its definition of the
word «object» is very similar to C’s, and is not limited to objects of
class type.</OT>

So /instance/ is not a technical word here, just plain English.

Advertisements

arnuld


  • #18

That usage has a long history. OOP is a johnny-come-lately; in any case,
where do you think they got the word «object» from in the first place?

From medical sciences ? where Doctors use to refer to patient as subject
and something else as object.

But long time ago before that object was already in English, something
like «I am the object of amusement»

Do you feel good about «j is a variable with type int»? Yet i and j
clearly have many (indeed, almost all) characteristics in common, and it
is useful to have a term that describes them both. «Object» is perfect
for that.

I wonder why did you use /const/. Anyway, I got confused because you
said /Object/ instead of /object/.

Я работаю над процессором Cell, и я пытаюсь создать структуру, которая будет содержать spe_context_ptr_t, который будет использоваться в потоке для запуска контекста spe, а также будет содержать указатель на что-то еще который будет передан в контекст spu из потока (в настоящее время я пытаюсь просто сделать его общим указателем, но на самом деле это будет указатель на другую структуру, которую я определил). Когда я пытаюсь скомпилировать, я получаю следующую ошибку:

spu/../common.h:38: error: expected specifier-qualifier-list before 'spe_context_ptr_t'

// here is the offending line(s)

typedef struct _PTHREAD_BLOCK {
    spe_context_ptr_t * context; // Error happens here
    uintptr32_t  args; 
 } PTHREAD_BLOCK;

4b9b3361

Ответ 1

Компилятор не знает, что spe_context_ptr_t является типом. Убедитесь, что соответствующий тип typedef находится в области, когда этот код скомпилирован. Возможно, вы забыли включить соответствующий заголовочный файл.

Ответ 2

У меня было такое же сообщение об ошибке, но решение отличается.

Компилятор анализирует файл сверху вниз.

Убедитесь, что структура определена, прежде чем использовать ее в другой:

typedef struct
{
    char name[50];
    wheel_t wheels[4]; //wrong, wheel_t is not defined yet
} car_t;

typedef struct
{
    int weight;
} wheel_t;

Ответ 3

Для проектов iPhone cocoa -touch:

У меня была эта проблема, и благодаря комментарию Эрика Фарраро я смог решить эту проблему. Я импортировал класс WSHelper.h во многих других моих классах. Но я также импортировал некоторые из тех же классов в свой WSHelper.h(круговой, как сказал Эрик). Итак, чтобы исправить это, я переместил импорт из моего файла WSHelper.h в файл WSHelper.m, так как они вообще не нужны в файле .h.

Ответ 4

Вы должны называть свою структуру следующим образом:

typedef struct car_t {

   char

   wheel_t

} car_t;

Ответ 5

Я получил его с контуром импорта:

---FILE B.h
#import "A.h"
@interface B{
  A *a;
}
@end

---FILE A.h
#import "B.h"
@interface A{      
}
@end

Ответ 6

Мне удалось разобраться с использованием исправления Gorgando, но вместо того, чтобы перемещать импорт, я прокомментировал каждый отдельно, построил приложение, а затем отредактировал его, пока я не избавился от них.

Ответ 7

@simpleBob

---FILE B.h
#import "A.h"
@interface B{
  A *a;
}
@end

---FILE A.h

@class B;

@interface A{      
}
@end

код выше помог мне разобраться. Может ли кто-нибудь объяснить, что здесь происходит?

Ответ 8

эта ошибка в основном возникает, когда вы используете объект перед его использованием.

  • Home
  • Forum
  • The Ubuntu Forum Community
  • Ubuntu Specialised Support
  • Development & Programming
  • Programming Talk
  • [SOLVED] C Programming + expected specifier-qualifier-list before [varname]

  1. C Programming + expected specifier-qualifier-list before [varname]

    I’m writing a simulation of a 4 stage pipelined processor for a class at school and this error is driving me up a wall. I’m more specifically interested in what the heck «expected specifier-qualifier-list before [varname]» means rather than just a fix for the code below. Anyway here’s the code (I’ve marked where I get the error):

    PHP Code:




    /*

     * cpu.h -- This file is for the model of the SCMP CPU.

     * Author: Grant Curell

     */

    #ifndef CPU_H

    #define CPU_H

    #include <time.h>

    #include "memory.h"

    #define NUM_REGS    32    // 32 registers

    #define true 1 //define the boolean value "true" to be 1

    #define false 0 //define the boolean value "false to be 0

    // struct for CPU

    typedef struct {

       
    int regs[NUM_REGS];    // CPU registers

       
    unsigned long long clock;    // 64-bit clock

       
    unsigned long long latched_clock;    // latched version of clock

       
    Memory memory;    // system memory

       
    int ip;        // instruction pointer

       
    int ir;        // instruction register

       
    IFID ifid//ONE ERROR IS RIGHT HERE

       
    IDEX idex;

       
    IDIF idif;

       
    EXWB exwb;

    CPU;
    // struct for IFID register

    // contains IP, IR, branchFlag, branchIP, stallFlag

    typedef struct {

        
    int ip;    //instruction pointer

        
    int ir;    //instruction register

    IFID;
    // struct for IDEX register

    // contains opcode, rd, operands, IP

    typedef struct {

        
    Instr *instr//THE OTHER IS HERE

        
    int opcode;

        
    int rd;

        
    int ip;

    IDEX;
    // struct for IDIF register

    // contains opcode, rd, operands, IP

    typedef struct {

        
    int stallflag;

        
    int branchIP;

        
    int branchFlag;

    IDIF;
    // struct for exid register

    // contains the result of the alu operation

    typedef struct {

        
    int rd;

    EXID;
    // struct for exwb register

    // contains ip

    typedef struct {

        
    int ip;

        
    int writeFlag;

        
    int opcode;

        
    int rd;

        
    int result;

    EXWB;
    // function prototypes

    int getRegCPU *cpuint reg );

    void setRegCPU *cpuint regint val );

    int getClklCPU *cpu );

    int getClkhCPU *cpu );

    void initCPU *cpuint argcchar *argv[] );

    void finishCPU *cpuclock_t elapsedTime );

    int simulateCycleCPU *cpu );
    #endif 



    Success is simply going from failure to failure without the loss of enthusiasm.
    -Winston Churchill


  2. Re: C Programming + expected specifier-qualifier-list before [varname]

    The problem is the order in which your structures are declared. You should declare your sub-structures over the main one. Else, the compiler reads your code from top to bottom and doesn’t know what IFID, IDEX, IDIF, EXWB stands for.

    Or you put the prototypes for your structures over the main one or you just place your sub-structures over the main one (CPU).

    Quote Originally Posted by nova47
    View Post

    I’m writing a simulation of a 4 stage pipelined processor for a class at school and this error is driving me up a wall. I’m more specifically interested in what the heck «expected specifier-qualifier-list before [varname]» means rather than just a fix for the code below. Anyway here’s the code (I’ve marked where I get the error):

    PHP Code:



    /*
     * cpu.h -- This file is for the model of the SCMP CPU.
     * Author: Grant Curell
     */

    #ifndef CPU_H
    #define CPU_H

    #include <time.h>
    #include "memory.h"

    #define NUM_REGS    32    // 32 registers
    #define true 1 //define the boolean value "true" to be 1
    #define false 0 //define the boolean value "false to be 0

    //Prototypes (Typedef) for structures

    typedef struct IFID IFID;
    typedef struct IDEX IDEX;
    typedef struct IDIF IDIF;
    typedef struct EXID EXID;
    typedef struct EXWB EXWB;// struct for CPU
    typedef struct {
       
    int regs[NUM_REGS];    // CPU registers
       
    unsigned long long clock;    // 64-bit clock
       
    unsigned long long latched_clock;    // latched version of clock
       
    Memory memory;    // system memory
       
    int ip;        // instruction pointer
       
    int ir;        // instruction register
       
    IFID ifid//ONE ERROR IS RIGHT HERE
       
    IDEX idex;
       
    IDIF idif;
       
    EXWB exwb;
    CPU;// struct for IFID register
    // contains IP, IR, branchFlag, branchIP, stallFlag
    struct IFID{
        
    int ip;    //instruction pointer
        
    int ir;    //instruction register
    };// struct for IDEX register
    // contains opcode, rd, operands, IP
    struct IDEX{
        
    Instr *instr//THE OTHER IS HERE
        
    int opcode;
        
    int rd;
        
    int ip;
    };
    // struct for IDIF register
    // contains opcode, rd, operands, IP
    struct IDIF{
        
    int stallflag;
        
    int branchIP;
        
    int branchFlag;
    };
    // struct for exid register
    // contains the result of the alu operation
    struct EXID{
        
    int rd;
    };
    // struct for exwb register
    // contains ip
    struct EXWB{
        
    int ip;
        
    int writeFlag;
        
    int opcode;
        
    int rd;
        
    int result;
    };
    // function prototypes
    int getRegCPU *cpuint reg );
    void setRegCPU *cpuint regint val );
    int getClklCPU *cpu );
    int getClkhCPU *cpu );
    void initCPU *cpuint argcchar *argv[] );
    void finishCPU *cpuclock_t elapsedTime );
    int simulateCycleCPU *cpu );#endif 



    Last edited by Firestom; April 9th, 2009 at 01:03 AM.

    Reason: Added corrected code

    «Sometimes love isn’t about how much someone suits you, but how much you’re willing to change to suit them»
    99% of bugs in Linux are right between the keyboard and the chair you’re currently sitting in!


  3. Re: C Programming + expected specifier-qualifier-list before [varname]

    Thank you so much got it up and running. I hate those errors that you stare at for half an hour and get nowhere and the answer was just that obvious :-p

    Success is simply going from failure to failure without the loss of enthusiasm.
    -Winston Churchill


  4. Re: C Programming + expected specifier-qualifier-list before [varname]

    That’s what the forum is for, dear user! If ever you’re stumped, you can ask anybody here to help you out, there’s no problem. People like me love when they can lend a hand to someone needing help, it makes us feel like we’re doing it good and make us feel intelligent!

    Keep us the good work, I didn’t quite understand what is does but good work. And for information, a type-specifier is the term used for the keywords that tell which type it is (int, double, char*, struct). If you make a little research on terms you don’t understand you might come up with a solution fast!

    «Sometimes love isn’t about how much someone suits you, but how much you’re willing to change to suit them»
    99% of bugs in Linux are right between the keyboard and the chair you’re currently sitting in!


  5. Re: C Programming + expected specifier-qualifier-list before [varname]

    Solved already but yeah for future note, C reads files top to bottom, so either your structs need to be in the right order or use the prototypes as above.

    BTW I didn’t catch in your code where you defined the type Instr. Where is that at?


  6. Re: C Programming + expected specifier-qualifier-list before [varname]

    It’s not defined in the code above. That’s only a small snippet of the entire program. Instr is defined in another filed aptly named instr.h. Actually the problem I’m having at the moment is that in the code I posted above I need to include instr.h (for the Instr definition) and in instr.h I need cpu.h (the code that I posted) because it needs the CPU struct definition so I haven’t decided how I’m going to fix that.

    Success is simply going from failure to failure without the loss of enthusiasm.
    -Winston Churchill


  7. Re: C Programming + expected specifier-qualifier-list before [varname]

    If you don’t need the whole CPU structu embedded in each Instr struct, you can define Instr like this:

    Code:

    typedef struct CPU CPU;
    
    typedef struct Instr {
       /* whatever */
       CPU* cpu;
       /* more members */
    } Instr;

    You can declare _pointers_ to incomplete types because all the compiler has to know is the size and alignment of the data type it’s going to put into the struct (which is sizeof(CPU*) == sizeof(void*)). You’d only need to have the complete definition when you try to do something like «my_instr.cpu->ip». This is a very usual way to deal with circular dependences.

    May the Source be with you.


  8. Re: C Programming + expected specifier-qualifier-list before [varname]

    What I ended up having to do was a forward declaration:

    PHP Code:


    /*
     * cpu -- This file is for the model of the SCMP CPU.
     * Author: Grant Curell
     */

    #ifndef CPU_H
    #define CPU_H

    #include <time.h>
    #include "memory.h"

    struct InstrStruct;#define NUM_REGS    32    // 32 registers
    #define true 1 //define the boolean value "true" to be 1
    #define false 0 //define the boolean value "false to be 0

    // struct for IFID register
    // contains IP, IR, branchFlag, branchIP, stallFlag

    typedef struct {
        
    struct InstrStruct *instr;
        
    int ir;
        
    int ip;
    IFID;// struct for IDEX register
    // contains opcode, rd, operands, IP
    typedef struct {
        
    struct InstrStruct *instr;
        
    int ip;
    IDEX;// struct for IDIF register
    // contains opcode, rd, operands, IP
    typedef struct {
        
    int stallFlag;
        
    int branchIP;
        
    int branchFlag;
    IDIF;// struct for exid register
    // contains the result of the alu operation
    typedef struct {
        
    int rd;
    EXID;// struct for exwb register
    // contains ip
    typedef struct {
        
    struct InstrStruct *instr;
        
    int result;
    EXWB;// struct for CPU
    typedef struct {
       
    int regs[NUM_REGS];    // CPU registers
       
    unsigned long long clock;    // 64-bit clock
       
    unsigned long long latched_clock;    // latched version of clock
       
    Memory memory;    // system memory
       
    int ip;        // instruction pointer
       
    int ir;        // instruction register
       
    IFID ifid;
       
    IDEX idex;
       
    IDIF idif;
       
    EXWB exwb;
       
    EXID exid;
    CPU;// function prototypes
    int getRegCPU *cpuint reg );
    void setRegCPU *cpuint regint val );
    int getClklCPU *cpu );
    int getClkhCPU *cpu );
    void initCPU *cpuint argcchar *argv[] );
    void finishCPU *cpuclock_t elapsedTime );
    int simulateCycleCPU *cpu );#endif 



    That got around having to include instr.h in cpu.h I just had to replace Instr *instr; with struct InstrStruct *instr;

    Success is simply going from failure to failure without the loss of enthusiasm.
    -Winston Churchill


Bookmarks

Bookmarks


Posting Permissions

Comments

@petdance

@petdance
petdance

changed the title
Build fails on both 5.0.5 and unstable branches under GCC

Build fails under GCC

Jul 31, 2019

jrast

added a commit
to jrast/lab
that referenced
this issue

May 3, 2020

@jrast

Seems like Redis >= 6.0.0 fail to build with the GCC version available on uberspace. Using clang works.

See redis/redis#6286

Note: This is up for discussion. I just tried to installing redis using this guide and it failed. Using clang worked. But maybe there is a better solution?

luto

pushed a commit
to Uberspace/lab
that referenced
this issue

May 3, 2020

@jrast

@luto

Seems like Redis >= 6.0.0 fail to build with the GCC version available on uberspace. Using clang works.

See redis/redis#6286

Note: This is up for discussion. I just tried to installing redis using this guide and it failed. Using clang worked. But maybe there is a better solution?

This was referenced

Jul 26, 2020

This was referenced

Jul 28, 2020

LarsMichelsen

added a commit
to tribe29/checkmk
that referenced
this issue

Dec 17, 2020

@LarsMichelsen

Redis 6.0 relied on C11 features that our gcc 10.1 compiler
is not able to handle. At least with the SLES 12 distros the
compilation is not possible.

The redis team has decided to step back from the C11 requirement
which makes redis 6.2 compatible with our compiler. To make it
work on all supported distros, we now use this pre-release and
will go to 6.2 as soon as possible.

Details can be found here:

redis/redis#6286
redis/redis#7509

Change-Id: I0221568301fc0849966443747687955d0013f72d

LarsMichelsen

added a commit
to tribe29/checkmk
that referenced
this issue

Dec 17, 2020

@LarsMichelsen

Redis 6.0 relied on C11 features that our gcc 10.1 compiler
is not able to handle. At least with the SLES 12 distros the
compilation is not possible.

The redis team has decided to step back from the C11 requirement
which makes redis 6.2 compatible with our compiler. To make it
work on all supported distros, we now use this pre-release and
will go to 6.2 as soon as possible.

Details can be found here:

redis/redis#6286
redis/redis#7509

Change-Id: I0221568301fc0849966443747687955d0013f72d

Понравилась статья? Поделить с друзьями:
  • Error expected primary expression before token перевод
  • Error expected declaration before token
  • Error expected class name before token
  • Error expected primary expression before token arduino
  • Error expected before token exit status 1 expected before token