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

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.8k8 gold badges110 silver badges191 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

86210 silver badges31 bronze badges

1

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).

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C2059

Compiler Error C2059

03/26/2019

C2059

C2059

2be4eb39-3f37-4b32-8e8d-75835e07c78a

Compiler Error C2059

syntax error : ‘token’

The token caused a syntax error.

The following example generates an error message for the line that declares j.

// C2059e.cpp
// compile with: /c
// C2143 expected
// Error caused by the incorrect use of '*'.
   int j*; // C2059

To determine the cause of the error, examine not only the line that’s listed in the error message, but also the lines above it. If examining the lines yields no clue about the problem, try commenting out the line that’s listed in the error message and perhaps several lines above it.

If the error message occurs on a symbol that immediately follows a typedef variable, make sure that the variable is defined in the source code.

C2059 is raised when a preprocessor symbol name is re-used as an identifier. In the following example, the compiler sees DIGITS.ONE as the number 1, which is not valid as an enum element name:

#define ONE 1

enum class DIGITS {
    ZERO,
    ONE // error C2059
};

You may get C2059 if a symbol evaluates to nothing, as can occur when /Dsymbol= is used to compile.

// C2059a.cpp
// compile with: /DTEST=
#include <stdio.h>

int main() {
   #ifdef TEST
      printf_s("nTEST defined %d", TEST);   // C2059
   #else
      printf_s("nTEST not defined");
   #endif
}

Another case in which C2059 can occur is when you compile an application that specifies a structure in the default arguments for a function. The default value for an argument must be an expression. An initializer list—for example, one that used to initialize a structure—is not an expression. To resolve this problem, define a constructor to perform the required initialization.

The following example generates C2059:

// C2059b.cpp
// compile with: /c
struct ag_type {
   int a;
   float b;
   // Uncomment the following line to resolve.
   // ag_type(int aa, float bb) : a(aa), b(bb) {}
};

void func(ag_type arg = {5, 7.0});   // C2059
void func(ag_type arg = ag_type(5, 7.0));   // OK

C2059 can occur for an ill-formed cast.

The following sample generates C2059:

// C2059c.cpp
// compile with: /clr
using namespace System;
ref class From {};
ref class To : public From {};

int main() {
   From^ refbase = gcnew To();
   To^ refTo = safe_cast<To^>(From^);   // C2059
   To^ refTo2 = safe_cast<To^>(refbase);   // OK
}

C2059 can also occur if you attempt to create a namespace name that contains a period.

The following sample generates C2059:

// C2059d.cpp
// compile with: /c
namespace A.B {}   // C2059

// OK
namespace A  {
   namespace B {}
}

C2059 can occur when an operator that can qualify a name (::, ->, and .) must be followed by the keyword template, as shown in this example:

template <typename T> struct Allocator {
    template <typename U> struct Rebind {
        typedef Allocator<U> Other;
    };
};

template <typename X, typename AY> struct Container {
    typedef typename AY::Rebind<X>::Other AX; // error C2059
};

By default, C++ assumes that AY::Rebind isn’t a template; therefore, the following < is interpreted as a less-than sign. You must tell the compiler explicitly that Rebind is a template so that it can correctly parse the angle bracket. To correct this error, use the template keyword on the dependent type’s name, as shown here:

template <typename T> struct Allocator {
    template <typename U> struct Rebind {
        typedef Allocator<U> Other;
    };
};

template <typename X, typename AY> struct Container {
    typedef typename AY::template Rebind<X>::Other AX; // correct
};
  • Remove From My Forums
  • Question

  • error C2059: syntax error : 'constant'
    
    HI
    i have a file named SharedCount.hxx.
    i this file i have a class that ovveride operator new.
    
    problem with this is when i want to use this class compiler generate this error
    
    error C2059: syntax error : 'constant'
    
    and error line point to operator new overloading.
    
    exactly this file is modified version of boost shared_ptr.i use these file in another projects without any problem(vs c++ 2010).
    
    please help me to solve this error.
    unfortunately original code is very very long to be posted here but if it is required i will post it compeletly
    *******************************************SharedCount.hxx Snippet****************************************************
    
        #include "stdafx.h"
        #include <memory> // std::auto_ptr, std::allocator
        #include <functional> // std::less
        #include <exception> // std::exception
        #include <new> // std::bad_alloc
        #include <typeinfo> // std::type_info in get_deleter
        #include <cstddef> // std::size_t
        #include "ILock.hxx"
        #include "ILMutex.hxx"
        template<class P, class D> class ICORE_API sp_counted_base_impl: public sp_counted_base
        {
        private:
        P ptr; // copy constructor must not throw
        D del; // copy constructor must not throw
        sp_counted_base_impl(sp_counted_base_impl const &);
        sp_counted_base_impl & operator= (sp_counted_base_impl const &);
        typedef sp_counted_base_impl<P, D> this_type;
        public:
        // pre: initial_use_count <= initial_weak_count, d(p) must not throw
        sp_counted_base_impl(P p, D d): ptr(p), del(d)
        {
        }
        virtual void dispose() // nothrow
        {
        del(ptr);
        }
        virtual void * get_deleter(std::type_info const & ti)
        {
        return ti == typeid(D)? &del: 0;
        }
        void * operator new(size_t)
        {
        return std::allocator<this_type>().allocate(1, static_cast<this_type *>(0));
        }
        void operator delete(void * p)
        {
        std::allocator<this_type>().deallocate(static_cast<this_type *>(p), 1);
        }
        };

    #WebCan Video Conference System Based ON SL#

Answers

  • Then it must be some other file (not yours) where the ‘new’ is redefined.

    No, the error is related to ‘#define new …’ only.

    You could:

    1) Seach for ‘#define new’ in files that are included. To trace the included files,
    set «Show Includes» setting in C/C++ properties of your project. When building, the Output Windows will contain all that files. Find your error in the ‘Output Window’ and search the related ‘included’ files
    for ‘#define new’.

    OR

    2) Exclude some files from building and comment-out portions of your code until the problem disappears

    OR

    3) Create a new project and reproduce the problem with minimum amount of code. Next, use steps (1) and (2) to find the problem.

    OR

    4) Place

    #undef new 

    to the top of your file. But I’m not sure it will work as the root cause of that problem is still there.

    • Marked as answer by

      Monday, July 16, 2012 8:53 AM

  • Amir110 wrote:

    i test it and error trigers during bulding.

    but i never override operator new in a whole of project except in  SharedCount.hxx.

    Put this line near the beginning of SharedCount.hxx:

    #define new ANYTHING

    You would get an error about macro redifinition. The error message would  point to the spot of the previous definition. This way, you’ll find out  where new is defined as a macro.


    Igor Tandetnik

    • Proposed as answer by
      Grigoriy Chudnov
      Sunday, July 15, 2012 7:34 PM
    • Marked as answer by
      Amir110
      Monday, July 16, 2012 8:53 AM

See more:

I was following the tutorial on this page[^], but after setting everything up just like it said, using the same IDE and eventually copying the exact code from the tutorial, I’m getting an : error C2059: syntax error : ‘constant’ error that points to the IDR_MYMENU MENU line of my resource file. I’m not sure what I need to or can change to make this work and get the same result.

resource.rc:

#include "test.h"

IDR_MYMENU MENU
BEGIN
    POPUP "&File"
    BEGIN
        MENUITEM "E&xit", ID_FILE_EXIT
    END

    POPUP "&Stuff"
    BEGIN
        MENUITEM "&Go", ID_STUFF_GO
        MENUITEM "G&o somewhere else", 0, GRAYED
    END
END

IDI_MYICON ICON "menu_one.ico"

test.h:

#define IDR_MYMENU 101
#define IDI_MYICON 201

#define ID_FILE_EXIT 9001
#define ID_STUFF_GO 9002

test.cpp:

#include "resource.rc"
#include <windows.h>
#include "test.h"

const char g_szClassName[] = "myWindowClass";

LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
    switch(Message)
    {
        case WM_COMMAND:
            switch(LOWORD(wParam))
            {
                case ID_FILE_EXIT:
                    PostMessage(hwnd, WM_CLOSE, 0, 0);
                break;
                case ID_STUFF_GO:
                    MessageBox(hwnd, "You clicked Go!", "Woo!", MB_OK);
                break;
            }
        break;
        case WM_CLOSE:
            DestroyWindow(hwnd);
        break;
        case WM_DESTROY:
            PostQuitMessage(0);
        break;
        default:
            return DefWindowProc(hwnd, Message, wParam, lParam);
    }
    return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{
    WNDCLASSEX wc;
    HWND hwnd;
    MSG Msg;

    wc.cbSize        = sizeof(WNDCLASSEX);
    wc.style         = 0;
    wc.lpfnWndProc   = WndProc;
    wc.cbClsExtra    = 0;
    wc.cbWndExtra    = 0;
    wc.hInstance     = hInstance;
    wc.hIcon         = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_MYICON));
    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
    wc.lpszMenuName  = MAKEINTRESOURCE(IDR_MYMENU);
    wc.lpszClassName = g_szClassName;
    wc.hIconSm       = (HICON)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_MYICON), IMAGE_ICON, 16, 16, 0);

    if(!RegisterClassEx(&wc))
    {
        MessageBox(NULL, "Window Registration Failed!", "Error!",
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    hwnd = CreateWindowEx(
        WS_EX_CLIENTEDGE,
        g_szClassName,
        "A Menu",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,
        NULL, NULL, hInstance, NULL);

    if(hwnd == NULL)
    {
        MessageBox(NULL, "Window Creation Failed!", "Error!",
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    while(GetMessage(&Msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }
    return Msg.wParam;
}

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Ошибка c2059 синтаксическая ошибка return
  • Ошибка c203f дэу нексия n150
  • Ошибка c2011 mazda
  • Ошибка c2010 kyocera 2040

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии