I get the error message :
error: a storage class can only be specified for objects and functions struct
in my header file..
/*
* stud.h
*
* Created on: 12.11.2013
* Author:
*/
//stud.h: Definition der Datenstruktur Stud
#ifndef _STUD_H
#define _STUD_H
struct Stud{
long matrnr;
char vorname[30];
char name[30];
char datum[30];
float note;
};
extern Stud mystud[];
int einlesen (struct Stud[]);
void bubbleSort(struct Stud[] , int );
void ausgeben(struct Stud[], int);
#endif
where is the problem?
asked Nov 12, 2013 at 17:06
7
I would say that your problem is with the
extern Stud mystud[];
It probably should change to something more like
extern struct Stud* mystud;
and then in the implementation file for this header:
struct Stud stud_storage[SIZE];
struct Stud* mystud = stud_storage;
I think you could possibly get away with the extern struct Stud mystud[];
declaration with some compilers that will always convert that internally the corresponding pointer type, but not with all compilers (Need to double check my ANSI standard (C89) to be sure, but the conversion is only allowed by the standard in function declarations and definitions not in variable declarations.)
Keith M
83310 silver badges27 bronze badges
answered Nov 12, 2013 at 17:30
diverscuba23diverscuba23
2,15718 silver badges32 bronze badges
0
-
11-16-2011
#1
Registered User
Compiler Error a storage class can only be specified for objects and functions
I have some code that I’ve successfully compiled in a couple of compilers. I am now trying to use CodeBlocks with the GCC compiler. I have a header file that declares a number of structures that are used in a DLL. The declarations look like this:
Code:
extern struct structure1 {float var1, double var2, int var3};
The numbers of variables in the structures and their precisions vary. But each one of them is generating the error in the tag line:
a storage class can only be specified for objects and functions
Why? How do I correct it? What is different between this compiler and something like VisualStudio where it builds successfully?
Thank you, in advance, for your help and suggestions.
-
11-16-2011
#2
Registered User
extern is used to inform the compiler that a particular object (variable) exists somewhere else. It can also be used on functions, although there is no syntactic point to do so.
You have neither an object/variable nor a function here, so extern is not allowed. As far as C is concerned, it has no meaning here. To fix it, remove the extern.
Why does Visual Studio accept it? Who knows.
-
11-18-2011
#3
Registered User
Thank you. I removed the extern and, as you said, the error disappears. It is very interesting that Borland, VS and Pelles all pass by that issue.
-
11-18-2011
#4
Registered User
is that really your code? or did you accidentally put commas instead of semicolons? in either case it doesn’t compile in visual c 2010
Я получаю сообщение об ошибке: ошибка: класс хранения может быть указан только для объектов и структур функций в моем заголовочном файле.
/*
* stud.h
*
* Created on: 12.11.2013
* Author:
*/
//stud.h: Definition der Datenstruktur Stud
#ifndef _STUD_H
#define _STUD_H
struct Stud{
long matrnr;
char vorname[30];
char name[30];
char datum[30];
float note;
};
extern Stud mystud[];
int einlesen (struct Stud[]);
void bubbleSort(struct Stud[] , int );
void ausgeben(struct Stud[], int);
#endif
в чем проблема?
1 ответы
Я бы сказал, что ваша проблема связана с
extern Stud mystud[];
Вероятно, это должно измениться на что-то более похожее на
extern struct Stud* mystud;
а затем в файле реализации для этого заголовка:
struct Stud stud_storage[SIZE];
struct Stud* mystud = stud_storage;
Я думаю, что вы могли бы уйти с extern struct Stud mystud[];
объявление с некоторыми компиляторами, которые всегда будут преобразовывать это внутренне в соответствующий тип указателя, но не со всеми компиляторами (необходимо дважды проверить мой стандарт ANSI (C89), чтобы быть уверенным, но преобразование разрешено стандартом только в объявлениях и определениях функций, а не в объявлениях переменных.)
Создан 28 ноя.
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
c++
or задайте свой вопрос.
- Forum
- UNIX/Linux Programming
- Error with Vector of Vectors of Custom s
Error with Vector of Vectors of Custom struct
|
|
Output:
|
|
I don’t know what I’m doing wrong. I’m trying to have a vector of vectors of a custom struct. Thanks in advance!
you cannot declare a struct static without directly creating an instance of it.
remove the static and everything should work
I’m still a little surprised about the error message…
this is the error Message I got:
error: a storage class can only be specified for objects and functions
Last edited on
I got that too. Scroll down to the bottom for my errors.
you only posted 8 lines of errors…
as I said, try to remove the keyword static
I did. I got those errors too, I just wasn’t worried about them. I still get the errors I said without static.
I was using it as a single vector, not a vector of vectors. Sorry. Thanks for helping.
Topic archived. No new replies allowed.
Topic: Stupid Noob Question (Read 4179 times)
I’m in the process of trying CodeBlocks for the very first time. I know this question is beyond stupid but I can’t seem to find the answer to it. I have a project set up and am getting an error on build that I believe is generated because CodeBlocks is compiling as if the code is C++ but it is C code. How do I set the compiler (I just have the GCC compiler installed) to build as C code?
Thank you for your help.
Logged
zabzonk
From the CB opening screen, choose «Create new project», then «console application», then select «C» (and not «C++») from the language options. This will create a project with a main.c file which will compile as C code. When adding further files to the project, make sure they have a .c extension and not a .cpp one.
Logged
Neil,
Thank you for the quick reply. I am trying to build a DLL. Should I just ignore that selection and still pick Console application? Or is there a way to select the DLL and still set it to C compile?
Logged
zabzonk
It looks like the DLL wizard does not have the language option. You just need to rename the file(s) manually to have the .c extension rather than .cpp, and then add the newly named files to the project.
Logged
The files do have a .c extension. Maybe the error is not a C++ error. But, I’ve had this exact same code compile in other compilers with no problem. It’s puking on declarations of extern structs.
Logged
Okay….my bad. Not a C++ error. I tried the Console C setup and I still get the error. This is the error and I don’t know why I’m getting it. Like I said, this compiles successfully elsewhere.
error: a storage class can only be specified for objects and functions
Logged
zabzonk
You need to ask questions about stuff like that elsewhere, I’m afraid.
Logged
Will do. Thank you for your time and attention. I appreciate it!
Logged
Hello all,
I’m getting trouble with a class that I just added:
extern class c_piece
{
public:
int rotation;
void rotate()
{
rotation++;
}
int x;
int y;
int arr_size [4] [4];
};
This is the error:
Quote:error: a storage class can only be specified for objects and functions
Here is all of the code (with Xcode project build if you have a Mac :)):
Link to files
Any ideas?
_______________________My computer stats:Xcode 3.1.2Mac OS 10.5.8—Visual C++ 2008 Express EditionWindows XP—NetBeansUbuntu 9.04—Help needed here!
Never used this language before… but…
Just based on the error, it sounds a lot like you’ll have to change the extern keyword, or else get rid of your fields (int x, y, arr_size)
This is just a total guess, hope it helps.
Quote:Original post by BubbaCola
Never used this language before… but…
Just based on the error, it sounds a lot like you’ll have to change the extern keyword, or else get rid of your fields (int x, y, arr_size)This is just a total guess, hope it helps.
Good guess. That extern thing wasn’t supposed to be there, though. It has a different error without the extern there, referencing to Other_functions.cpp, saying that basically the class is not defined there. Soooo… how do I get it to be defined in both files?
_______________________My computer stats:Xcode 3.1.2Mac OS 10.5.8—Visual C++ 2008 Express EditionWindows XP—NetBeansUbuntu 9.04—Help needed here!
It looks like you’re trying to use the global variable curr_piece in Other_Functions.cpp. You need to add this line to sdl_t002.h
extern c_piece curr_piece;
You need to use the extern keyword for global instances of a class, but not on the class definition itself.
Ok, so what you wrote got me to thinking, and I got it fixed. The problem was in that I didn’t properly define something directly above where I defined the class. Thanks for the help!
adam_o
EDIT: Meh, I posted after pi_equals_3, but I came to the same conclusion as him. Thanks!
_______________________My computer stats:Xcode 3.1.2Mac OS 10.5.8—Visual C++ 2008 Express EditionWindows XP—NetBeansUbuntu 9.04—Help needed here!
The remaining compiler problems arise from notepad++ specific extensions, not from the original scintilla source code.
Most could be fixed by the change in WordList.h:
change:
void WordList::SetWordAt(int n, const char word2Set) {
to:
void SetWordAt(int n, const char word2Set) {
Explanation for «error: extra qualification» see here:
http://stackoverflow.com/questions/11692806/error-extra-qualification-student-on-member-student-fpermissive
The next one is in LexUser.cxx:
../lexers/LexUser.cxx:933:25: error: ‘>>’ should be ‘> >’ within a nested template argument list
Explanation for this error type see here:
http://stackoverflow.com/questions/6695261/template-within-template-why-should-be-within-a-nested-template-arg
Fix proposal:
change:
typedef vector<vector<string>> vvstring;
to:
typedef vector<vector<string> > vvstring;
Remaining problem in LexUser.cxx:
../lexers/LexUser.cxx:1657:47: error: third operand to the conditional operatoris of type ‘void’, but the second operand is neither a throw-expression nor of type ‘void’
This refers to the following for-loop syntax:
for (; finished; dontMove?true:sc.Forward())
Probably recent gcc versions do not like this syntax; see here:
http://compgroups.net/comp.lang.c++/minor-compiler-bug/1050777
Seems that the expression need to be replaced by an if-else ??
The next and last one is about LexSearchResult.cxx:
../lexers/LexSearchResult.cxx:43:86: error: a storage class can only be specified for objects and functions
and some others. — All that is caused by the statement:
static enum { searchHeaderLevel = SC_FOLDLEVELBASE + 1, fileHeaderLevel, resultLevel };
About that, see http://stackoverflow.com/questions/4971436/c-what-does-static-enum-mean
Or: http://forums.codeguru.com/showthread.php?357248-error-quot-storage-class-can-only-be-specified-for-objects-and-functions-quot
Fix proposal via last link: «You don’t need the static keyword there»
Closed
Bug 1330481
Opened 6 years ago
Closed 6 years ago
Categories
(Core :: Fuzzing, defect)
Tracking
()
Tracking | Status | |
---|---|---|
firefox53 | — | fixed |
People
(Reporter: glandium, Assigned: glandium)
Details
Attachments
(1 file)
When building with --enable-fuzzing with GCC, I get the following error: LibFuzzerTestHarness.h:78:1: error: a storage class can only be specified for objects and functions static class ScopedXPCOM : public nsIDirectoryServiceProvider2 ^~~~~~
You need to log in
before you can comment on or make changes to this bug.
Я пытаюсь создать глобальный класс, чтобы я мог получить к нему доступ в любом месте, но он не работает, я получаю сообщение об ошибке:
a storage class can only be specified for objects and functions
Кто-нибудь знает, где я иду не так?
Вот мой файл h:
extern class Payments : public QObject
{
Q_OBJECT
public:
Payments(QObject *parent = 0);
virtual ~Payments();
void purchase(const QString &id, const QString &sku, const QString &name, const QString &metadata);
void getExisting(bool refresh);
void getPrice(const QString &id, const QString &sku);
public slots:
void purchaseResponse();
void existingPurchasesResponse();
void priceResponse();
signals:
void purchaseResponseSuccess(const QString &receiptString);
void existingPurchasesResponseSuccess(const QString &receiptsString);
void priceResponseSuccess(const QString &price);
void infoResponseError(int errorCode, const QString &errorText);private:
bb::platform::PaymentManager *paymentManager;
};
2
Решение
Ключевое слово класса хранения extern
вызывает проблему. Вы не можете указать это для определения класса. И все равно вам это не нужно: ваше определение класса будет доступно из любой точки мира (при условии, что вы #include
файл, в котором он определен).
4
Другие решения
Вам не нужно extern
и в C ++ даже не разрешено объявлять классы как внешние. Любой класс доступен из любого другого места, если только вы не связываетесь с флагами видимости, специфичными для компилятора, и несколькими общими объектами (т.е. GCC видимость) и не создавайте вложенный, защищенный или закрытый класс.
3
C++
позволяет использовать extern
только для объектов или функций.
1
Для классов концепция «глобального» на самом деле не имеет большого смысла: классы объявляются везде, где они объявлены, и все. Таким образом, классификация хранилища не допускается при определении класса: необходимо удалить extern
,
Чтобы сделать определение класса общедоступным, вам нужно включить его определение в каждую единицу перевода, где вы хотите получить доступ к классу. Способ сделать это — поместить его в заголовочный файл и включать в него всякий раз, когда вам нужен класс:
#ifndef INCLUDED_PAYMENTS
#define INCLUDED_PAYMENTS
// headers needed to define Payments
class Payments : public QObject
{
...
};
#endif INCLUDED_PAYMENTS
Чтобы избежать конфликтов имен, вам следует рассмотреть возможность объявления вашего класса в пространстве имен: определения классов в программе на C ++ должны быть уникальными. То есть, если другой файл, не содержащий вышеуказанный заголовок, также определяет класс Payments
в глобальном пространстве имен, но в некотором роде иное, это будут противоречивые определения. Однако компилятору не требуется обнаруживать различные варианты использования, что может затруднить диагностику проблем.
1