Синтаксическая ошибка константа

I've got a piece of code that's automatically generated that compiles on Linux but not on Windows using Visual Studio 2008 Express. The issue I'm having is that I don't understand the compiler erro...

I’ve got a piece of code that’s automatically generated that compiles on Linux but not on Windows using Visual Studio 2008 Express. The issue I’m having is that I don’t understand the compiler error. I don’t think I can post the exact code, so here’s a sanitized version of it…

Error is reported for the line declaring the static const DELETE. Note: The compiler error doesn’t show up when this file is compiled — it builds into a library successfully, but shows up in a second project that includes the header (indirectly). I believe there are at least one or two other projects that include it indirectly in the solution — they have no issues compiling.

File_A.h:

enum LONG_TYPE_NAME {
  ENUM_NAME_PREFIX_ADD = 0,
  ENUM_NAME_PREFIX_CHANGE = 1,
  ENUM_NAME_PREFIX_DELETE = 2,
  ENUM_NAME_PREFIX_SOMETHINGELSE = 3,
};
//Lots of code here
class FOO : public ::LIBRARY_NAME {
 public:
  //Some stuff
  private:
  //Some stuff
  public:
  //Some more stuff

  typedef LONG_TYPE_NAME SHORT_NAME;
  static const SHORT_NAME ADD = ENUM_NAME_PREFIX_ADD;
  static const SHORT_NAME CHANGE = ENUM_NAME_PREFIX_CHANGE; 

  /* compiler error for the following line only*/
  static const SHORT_NAME DELETE = ENUM_NAME_PREFIX_DELETE; 
  static const SHORT_NAME SOMETHINGELSE = ENUM_NAME_PREFIX_SOMETHINGELSE; 

  //More stuff
};

The constant itself only shows up in one place (when I search through the project for the term DELETE):

File_A.cc:

#ifndef _MSC_VER
const LONG_TYPE_NAME FOO::ADD;
const LONG_TYPE_NAME FOO::CHANGE;
const LONG_TYPE_NAME FOO::DELETE;
//More stuff
#endif  // _MSC_VER

The error reported is error C2059: syntax error : 'constant' (followed by error C2258: illegal pure syntax, must be '= 0' and error C4430: missing type specifier - int assumed. Note: C++ does not support default-int which I assume are not relevant), but not when the files above are being compiled.

The files are compiled to a library which is statically linked to by another project (C++) — this is the one that’s generating the error (as well as in a second .cpp file that does something similar). It still shows up when I comment out all the code, so I assume it has something to do with header inclusions.

Commenting out the line generating the error makes the build work on Windows (and fail on Linux, but I assume that commenting out its counterpart in the ifndef should fix that), but I really want to know why the compiler is failing for that particular line and what the error actually means. Also, it’s probably better not to modify code that’s been automatically generated.

EDIT: Splitting up the terms into individual lines makes the compiler point to the DELETE line. Maybe there’s a macro automatically defined with the name DELETE somewhere?

EDIT 2: Cleaned up the heading section a bit to clear up some possible misconceptions.
Incidentally, renaming the DELETE variable also clears out the error.

EDIT 3: Clearly I need to learn more about VS — /P generates the preprocessed file without producing the object file, so the build will of course fail without generating compilation errors. Also, it does look like there is a macro somewhere, which defines DELETE as (0x00010000L).

I’ve got a piece of code that’s automatically generated that compiles on Linux but not on Windows using Visual Studio 2008 Express. The issue I’m having is that I don’t understand the compiler error. I don’t think I can post the exact code, so here’s a sanitized version of it…

Error is reported for the line declaring the static const DELETE. Note: The compiler error doesn’t show up when this file is compiled — it builds into a library successfully, but shows up in a second project that includes the header (indirectly). I believe there are at least one or two other projects that include it indirectly in the solution — they have no issues compiling.

File_A.h:

enum LONG_TYPE_NAME {
  ENUM_NAME_PREFIX_ADD = 0,
  ENUM_NAME_PREFIX_CHANGE = 1,
  ENUM_NAME_PREFIX_DELETE = 2,
  ENUM_NAME_PREFIX_SOMETHINGELSE = 3,
};
//Lots of code here
class FOO : public ::LIBRARY_NAME {
 public:
  //Some stuff
  private:
  //Some stuff
  public:
  //Some more stuff

  typedef LONG_TYPE_NAME SHORT_NAME;
  static const SHORT_NAME ADD = ENUM_NAME_PREFIX_ADD;
  static const SHORT_NAME CHANGE = ENUM_NAME_PREFIX_CHANGE; 

  /* compiler error for the following line only*/
  static const SHORT_NAME DELETE = ENUM_NAME_PREFIX_DELETE; 
  static const SHORT_NAME SOMETHINGELSE = ENUM_NAME_PREFIX_SOMETHINGELSE; 

  //More stuff
};

The constant itself only shows up in one place (when I search through the project for the term DELETE):

File_A.cc:

#ifndef _MSC_VER
const LONG_TYPE_NAME FOO::ADD;
const LONG_TYPE_NAME FOO::CHANGE;
const LONG_TYPE_NAME FOO::DELETE;
//More stuff
#endif  // _MSC_VER

The error reported is error C2059: syntax error : 'constant' (followed by error C2258: illegal pure syntax, must be '= 0' and error C4430: missing type specifier - int assumed. Note: C++ does not support default-int which I assume are not relevant), but not when the files above are being compiled.

The files are compiled to a library which is statically linked to by another project (C++) — this is the one that’s generating the error (as well as in a second .cpp file that does something similar). It still shows up when I comment out all the code, so I assume it has something to do with header inclusions.

Commenting out the line generating the error makes the build work on Windows (and fail on Linux, but I assume that commenting out its counterpart in the ifndef should fix that), but I really want to know why the compiler is failing for that particular line and what the error actually means. Also, it’s probably better not to modify code that’s been automatically generated.

EDIT: Splitting up the terms into individual lines makes the compiler point to the DELETE line. Maybe there’s a macro automatically defined with the name DELETE somewhere?

EDIT 2: Cleaned up the heading section a bit to clear up some possible misconceptions.
Incidentally, renaming the DELETE variable also clears out the error.

EDIT 3: Clearly I need to learn more about VS — /P generates the preprocessed file without producing the object file, so the build will of course fail without generating compilation errors. Also, it does look like there is a macro somewhere, which defines DELETE as (0x00010000L).

I am getting the following errors when compiling the below code:

3>c:hedgehedgehedgeAisTarget.h(22) : error C2059: syntax error : 'constant'
3>c:hedgehedgehedgeAisTarget.h(22) : error C2238: unexpected token(s) preceding ';'

#if !defined(AisTarget_h)
#define AisTarget_h

#include "GeneralAviationItems.h"
#include <string>

namespace HEDGE {
    using namespace GeneralAviation; 

    class AisTarget : public WaypointLatLon {
        public:
            static const int NO_DATA = -1000; //here is the error
    };    
} // end namespace HEDGE

#endif

Fantastic Mr Fox's user avatar

asked Aug 2, 2012 at 16:41

user1572019's user avatar

3

It is likely that NO_DATA is already defined as a macro elsewhere, and so it is expanding into something that does not agree with the compiler’s notion of a variable name. Try re-naming NO_DATA to something else.

If there were no such conflict, the code as it were would compile fine, as demonstrated here.

answered Aug 2, 2012 at 16:45

jxh's user avatar

jxhjxh

68.1k7 gold badges109 silver badges186 bronze badges

3

Even if this post has its age: The error can generally occur when multiple redefinitions, even regardless of upper/lower case, coexist. This includes potential preprocessor definitions in the solution’s .vcprojx file!. Consider something like

  <ItemDefinitionGroup>
    <ClCompile>
      <PreprocessorDefinitions>$(Configuration);%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </ClCompile>
  </ItemDefinitionGroup>

in the above mentioned file. Now, having «Debug» and «Release» configurations you will most probably run into some problems and a potential source for the C2059 error. I experienced exaclty this dilemma.

answered Apr 21, 2016 at 7:32

gilgamash's user avatar

gilgamashgilgamash

83210 silver badges29 bronze badges

1

takeiteasy

0 / 0 / 0

Регистрация: 15.10.2011

Сообщений: 10

1

14.12.2011, 20:47. Показов 4876. Ответов 1

Метки нет (Все метки)


Подскажите пожалуйста почему выдает ошибку error C2059: syntax error : ‘constant’
в этой строке :

C++
1
const int OK=0, EOS=0, ERROR=0;

пробовала через enum — тоже ошибки выдает.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include "stdafx.h"
#include <iostream>
using namespace std;
 
 
const int OK=0, EOS=0, ERROR=0;
int get(int &x) 
{
static bool isCurrent=true;
static double current;
static double first;
double y;
if (isCurrent) cout<<"Enter real:n";
else cout<<"Enter real("<<current<<" to finish) :n";
if (!(cin>>y)) return ERROR; 
if (isCurrent)
  { isCurrent=false; current=y; x=y; return OK; }
else
  { if (y==false) return EOS;
x=y; return OK;
  }
}
 
 
 
int main ()
{ 
int get(int &x);
    
    system ("pause");
    return 0;
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



dino-4udo

-5 / 6 / 4

Регистрация: 16.12.2010

Сообщений: 68

14.12.2011, 20:57

2

Попробуй так

C++
1
const int OK==0, EOS==0, ERROR==0;



0



  • Forum
  • Beginners
  • syntax error : ‘constant’

syntax error : ‘constant’

Not really sure why im getting this error. Basically, in class state
i am trying to instantiate a Graphics object.

Graphics constructor

1
2
3
4
5
6
Graphics::Graphics( int screenWidth, int screenHeight, int screenBPP, std::string Caption)
{
	SDL_Init(SDL_INIT_VIDEO);
	screen = SDL_SetVideoMode( screenWidth, screenHeight, screenBPP, SDL_SWSURFACE );
	SDL_WM_SetCaption( Caption.c_str(), NULL );
}

class State

1
2
3
4
5
6
7
8
9
10
class State
{
public:
	virtual void HandleEvents() = 0;
	virtual void Logic() = 0;
	virtual void Render() = 0;

	Graphics* graphics( 640, 480, 32, "MyGame" );
	GameState nextState;
};

You can’t initialize it in your declaration, and It’s a pointer, also I’d suggest you not use any namespaces in headers.

The reason why it mentioned constant is because only constant static variables can be initialized in the class declaration scope.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class State
{
public:
   virtual void HandleEvents() = 0;
   virtual void Logic() = 0;
   virtual void Render() = 0;

   Graphics* graphics;
   GameState nextState;
             
   State();
};

State::State()
{
   graphics = new Graphics( 640, 480, 32, "MyGame" );
}

Last edited on

You can’t construct members in class bodies like that*. You’ll have to put that in the constructor.

(*at least not yet, I think the C++11 standard allows it, but you’re still doing it wrong because you have a pointer and not an object).

Although, I won’t directly answer your question because I suspect you are doing something you shouldn’t.

Your ‘graphics’ object probably shouldn’t be owned by the State like that. Since you will have many states, they will all want to share the same Graphics object. If they are each creating their own, that means you will be creating a new window for each state! Not something you want.

Your ‘Game’ class (or something similar) should own the graphics, then pass a pointer to it to each state. Or maybe instead, it should be a parameter passed to Render, since that’s the only time you’ll need it anyway.

EDIT:

Looks like I was too slow and Turbine already answered.

Please heed by warning though: you don’t want each State to have its own Graphics. That is very weird and will not do what you want.

Last edited on

@ disch

Thanks for the help but i need to be able to use Graphics functions in each states Constructor, Destructor, and Render function.

I tried making a Graphics object in main, and then passing that to each states constructor but that doesnt work. I’m not sure what else to try.

OK, you’re going to have stuff that you want to share between all states, right? Things like game settings (use configurable stuff like controls and whatever), graphics, and maybe some other stuff.

Throw all of that in a struct. Your game should have 1 instance of that struct that it passes around between states.

Something like this:

1
2
3
4
5
6
struct Environment
{
  Graphics* graphics;
  UserSettings settings;
  WhateverElse foobar;
};

Your Game or similar class (or I guess main() if you don’t have a Game class) would create the graphics and put a pointer to it in the struct. I wouldn’t recommend putting the actual graphics object in the struct, just a pointer.

1
2
3
4
5
6
7
8
9
10
int main()
{
  Graphics theGraphics( ... whatever ... );
  Environment theGameEnvironment;

  theGameEnvironment.graphics = &theGraphics;

  // now give the environment to your states when they're created
  GameState* currentState = new WhateverState( &theGameEnvironment );
}

Your State ctors would then need to take an Environment* as a parameter. You can then access the graphics (and other shared info) through that pointer.

I feel so close Disch!! But it still doesnt work, maybe a did it wrong. Graphics is not working in the state classes( says «graphics» is undefined ) .

I created Environment.h to hold the Environment struct.

in main i did this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
int main( int argc, char** argv )
{
	Graphics graphics( 640, 480, 32, "MyGame" );
	Environment GameEnvironment;

	GameEnvironment.graphics = &graphics;

	currentState = new Intro( &GameEnvironment );

	while( currentState->nextState != STATE_EXIT)
	{
		currentState->HandleEvents();
		currentState->Logic();
		currentState->Render();

		//if needed, change state
		switch( currentState->nextState )
		{
		case STATE_MENU:
			delete currentState;
			currentState = new Menu( &GameEnvironment );
			break;
		/*case STATE_GAME:
			delete currentState;
			currentState = new Game();
			*/
		}
	}

and the constructors for the states look like this

1
2
3
4
5
6
Intro::Intro( Environment* GameEnvironment  )
{
	
	introImage = graphics->LoadImage( "Media/introBG.bmp" );
	fading[0]  = graphics->LoadImage( "Media/introFade_0.bmp" );
}

In your state classes, since graphics is in the Environment struct, it would be

 
GameEnvironment->graphics->LoadImage(

I did that, but it only works in the Constructors. The rest of the functions dont work

Intro::Intro( Environment* GameEnvironment )
{

introImage = graphics->LoadImage( «Media/introBG.bmp» );
fading[0] = graphics->LoadImage( «Media/introFade_0.bmp» );
}

For all pointer related variables, always place a pointer valid check before de-referencing them.

e.g

1
2
3
4
5
6
7
8
if (GameEnvironment) {
  Graphics graphics = GameEnvironment->graphics;
  if (graphics) {  
    introImage = graphics->LoadImage( "Media/introBG.bmp" );
    fading[0]  = graphics->LoadImage( "Media/introFade_0.bmp" );
  } esle cout << "graphics is null!n";
} else cout << "GameEnvironment is nul!n";

nano511 wrote:
I did that, but it only works in the Constructors. The rest of the functions dont work

That’s because GameEnvironment is a parameter. Which makes it local to the constructor.

If you want it to work in the rest of the functions, you’ll need to make it available in the rest of the functions =P. Read up on scope rules and member variables.

Basically you need to make a member variable for your states (probably an Environment* whatever), then set that pointer to GameEnvironment in the constructor. Then you can use ‘whatever’ anywhere in your state class.

sohguanh wrote:
For all pointer related variables, always place a pointer valid check before de-referencing them.

Meh. I don’t agree. Unnecessary extra code and overhead.

yeah disch i made a Graphics object in each state, then in the constructors it looks like

1
2
3
4
5
6

contructor( Environment* gameEnvironment )
{
     graphics = gameEnvironment.graphics;
}

There you go. Although I would recommend making an Environment* in each state instead of a Graphics*, since you’ll probably want to have access to more than just the graphics.

Or if all you need is the graphics, then don’t bother with the Environment struct at all anywhere and just pass a graphics pointer (I recommended the Environment struct because I figured you’d want to share other things — but if not then it doesn’t make much sense to have it)

Last edited on

yeah im just doing it like that for now. Now i just need to get rid of these LNK errors :(

sohguanh wrote:
For all pointer related variables, always place a pointer valid check before de-referencing them.

Meh. I don’t agree. Unnecessary extra code and overhead.

Well if it is a C++ program, we can pass in by reference then there is no extra code and overhead.

 
Intro::Intro( Environment& GameEnvironment)

In fact passing by reference is highly recommended for new C++ program who does not have to deal with legacy C code baggage.

Topic archived. No new replies allowed.

2 ответа

Вероятно, что NO_DATA уже определен как макрос в другом месте, и поэтому он расширяется во что-то, что не согласуется с понятием компилятора имени переменной. Попробуйте переименовать NO_DATA в другое.

Если такого конфликта не было, код как бы компилировался бы отлично, как показано здесь.

jxh
02 авг. 2012, в 17:05

Поделиться

Даже если этот пост имеет свой возраст: ошибка может вообще возникать, когда сосуществуют несколько переопределений, даже несмотря на верхний/нижний регистр. Это включает в себя потенциальные определения препроцессора в файле .vcprojx.!. Рассмотрим что-то вроде

  <ItemDefinitionGroup>
    <ClCompile>
      <PreprocessorDefinitions>$(Configuration);%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </ClCompile>
  </ItemDefinitionGroup>

в вышеупомянутом файле. Теперь, имея конфигурации «Debug» и «Release», вы, скорее всего, столкнетесь с некоторыми проблемами и потенциальным источником ошибки C2059. Я столкнулся с этой дилеммой.

gilgamash
21 апр. 2016, в 08:46

Поделиться

Ещё вопросы

  • 0FullCalendar: открыть событие gcal в новой вкладке / окне
  • 0JQuery, если / еще предупреждение, изменить цвет в зависимости от ответа
  • 0ng-show не реагирует на $ scope.apply
  • 1Как украсить TableCellRenderer инструкциями, связанными с графикой?
  • 0угловой тест не выполняет код директивы
  • 0Сетка углового интерфейса: уведомить пользователя, что сортировка может занять некоторое время
  • 1чтение байтов без использования цикла
  • 0Загрузка дополнительных сообщений не работает
  • 0Заставить браузер открывать новые окна в стиле SW_HIDE?
  • 0Как удалить массовый динамический формат даты в PHP?
  • 1Как долго длится мой подкласс класса Android «Приложение»?
  • 0JQuery: изменить значение CSS, если опция выбрана
  • 1Изменение данных адаптера
  • 1ASP.Net MVC 4 Razor — просмотр результатов поиска на веб-сетке
  • 0Обрезать HTML в Excel и заполнить разные ячейки
  • 1Как мне отформатировать SPARQL для JS?
  • 0CSRF токены добавляются в запросы
  • 0Изменение размера DIV делает текстовое поле на новой строке
  • 0Расширение Magento Checkout — перейти к следующему шагу в Checkout
  • 0По центру выровнять div, который имеет float: left
  • 1Вопрос макета — как начать действие, не перемещая определенные элементы интерфейса?
  • 1Python разница между оператором и функцией
  • 0Обеспечение безопасности типов в существующих навязчивых связанных списках C
  • 1Android — Макет вопроса — Textviews верхний центр и нижний центр
  • 0Внешняя ссылка не работает в FF, Chrome, но работает в IE 9
  • 0Использование SWIG для возврата Byte [], вызывающего jvm для segv при выходе
  • 0Как выполнить несколько запросов в sqlapi ++ с оракулом
  • 1Удалите цвет фокуса по умолчанию из GridLayout и EditBox в Android
  • 1извлечение из вложенного JSON с Python
  • 0bower.json и package.json интерполяция
  • 1Распознавание голоса с Android
  • 0Возникли проблемы с вложенным JOIN
  • 1Как создать экземпляр класса по имени строки
  • 0JQuery не проверяет формат электронной почты
  • 1Java лучший способ хранить значения из матрицы int по конкретным значениям
  • 0Как работает gulp and bower в asp.net mvc5
  • 0как выбрать имя столбца вместе с примененной к нему агрегатной функцией
  • 1Cloud ML Engine и Scikit-Learn: у объекта ‘LatentDirichletAllocation’ нет атрибута ‘предвидеть’
  • 0AngularJS ngRoute прямой доступ к деталям
  • 0Ошибка в синтаксисе SQL при попытке найти записи на расстоянии
  • 1Запуск приложения на эмуляторе под управлением более старого SDK
  • 0получить идентификатор элемента click в данный момент и получить идентификатор детей
  • 1Ошибка панд. Почему мои объекты смешанного типа?
  • 0Найти количество столбцов с одинаковым значением
  • 0Получение PHP регистрационной формы для связи с MYSQL
  • 1Что не так в моем решении N-Queens?
  • 1Элементы ListView не будут отображать фокус при прикосновении
  • 0PHP пост-запрос
  • 0Ошибка: [ng: areq] Аргумент ‘searchCtrl’ не является функцией, получил неопределенное значение
  • 1Поток Java и синхронизированный список

Понравилась статья? Поделить с друзьями:
  • Синий экран смерти ошибка 0х00000116 как исправить
  • Синтаксическая ошибка код 800a03ea
  • Синий экран смерти ошибка 0х0000007в
  • Синтаксическая ошибка как убрать
  • Синий экран смерти ошибка 0х0000007f