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 };
Solved
When I try to compile this program i keep getting these errors:
(50) : error C2059: syntax error :
‘<=’(50) : error C2143: syntax error
: missing ‘;’ before ‘{‘(51) : error
C2059: syntax error : ‘>’(51) : error
C2143: syntax error : missing ‘;’
before ‘{‘(62) : error C2059: syntax
error : ‘else’(62) : error C2143:
syntax error : missing ‘;’ before ‘{‘
#include <iostream>
#include <string>
#include <cassert>
using namespace std;
class income {
private:
double incm;
double subtract;
double taxRate;
double add;
char status;
public:
void setStatus ( char stats ) { status = stats; }
void setIncm (double in ) { incm = in; }
void setSubtract ( double sub ) { subtract = sub; }
void setTaxRate ( double rate ) { taxRate = rate; }
void setAdd ( double Add ) { add = Add; }
char getStatus () { return status; }
double getIncm () { return incm; }
double getsubtract () { return subtract; }
double getTaxRate () { return taxRate; }
double getAdd () { return add; }
void calcIncome ();
};
//calcIncome
int main () {
income _new;
double ajIncome = 0, _incm = 0;
char status = ' ';
bool done = false;
while ( !done ) {
cout << "Please enter your TAXABLE INCOME:n" << endl;
cin >> _incm;
if(cin.fail()) { cin.clear(); }
if ( _incm <= 0) { cout << "the income must be greater than 0... n" << endl; }
if ( _incm > 0) { done = true; _new.setIncm(_incm); }
}
done = false;
char stt [2] = " ";
while ( !done ) {
cout << "Please declare weather you are filing taxes jointly or single" << "n";
cout << "t's' = singlent'm' = married" << endl;
cin >> stt;
if(cin.fail()) { cin.clear(); }
if ( status == 's' || status == 'm' ) { done = true; _new.setStatus(stt[0]); }
//if else { }
}
return 0;
};
This is part of a homework assignment so any pointers on bettering my programing would be **great**
Note:I am using Windows 7 with VS express C++ 2008
asked Jan 13, 2010 at 15:44
WallterWallter
4,2656 gold badges29 silver badges33 bronze badges
3
income
is the name of your class. _incm
is the name of your variable. Perhaps you meant this (notice the use of _incm
not income
):
if (_incm <= 0) { cout << "the income must be greater than 0... n" << endl; }
if (_incm > 0) { done = true; _new.setIncm(_incm); }
Frequently you use CamelCase for class names and lowercase for instance variable names. Since C++ is case-sensitive, they wouldn’t conflict each other if they use different case.
answered Jan 13, 2010 at 15:47
Jon-EricJon-Eric
16.7k9 gold badges64 silver badges96 bronze badges
Your variable is named incom
, not income
. income
refers to a type, so the compiler gets confused and you get a syntax error when you try to compare that type against a value in line 50.
One note for bettering you programming would be to use more distinct variable names to avoid such confusions…
answered Jan 13, 2010 at 15:46
sthsth
218k53 gold badges277 silver badges364 bronze badges
1
BeyB 0 / 0 / 0 Регистрация: 28.10.2014 Сообщений: 23 |
||||
1 |
||||
28.10.2014, 17:52. Показов 4084. Ответов 8 Метки нет (Все метки)
У меня проблема в этом коде , подскажите пожалуйста что нужно исправлять вот сам код
а вот ошибка 1>—— Сборка начата: проект: Проект3, Конфигурация: Debug Win32 ——
__________________
0 |
Вездепух 10435 / 5704 / 1553 Регистрация: 18.10.2014 Сообщений: 14,098 |
|
28.10.2014, 17:59 |
2 |
Что такое ‘if else’??? Это бессмысленная белиберда. Очевидно имелось в виду ‘else if’… Отдельно стоит заметить, что скорее всего от вас ожидали, что вы напечатаете сами решения квадратного уравнения, а не формулы для решения из учебника. P.S. Ваша манера объединять последовательные выводы в ‘cout’ через оператор ‘&&’ остроумна, но вызывает удивление в коде у автора, который путает ‘if else’ с ‘esle if’.
0 |
5 / 5 / 5 Регистрация: 16.12.2013 Сообщений: 463 |
|
28.10.2014, 18:01 |
3 |
Что-то у вас тут не то. Во первых я вижу,что пропущена точка с запятой в 22 строке. Ну и если вы хотите,чтобы формулы записанные в cout работали,то их не нужно брать в кавычки. Добавлено через 25 секунд
0 |
0 / 0 / 0 Регистрация: 28.10.2014 Сообщений: 23 |
|
28.10.2014, 18:12 [ТС] |
4 |
спасибо за помощь но я совсем уже запутался, мне надо собрать прогу которая должен решить дискриминант , а у мя Бог знает что получился , может поможете , обясните что к чему ?
0 |
Вероника99 5 / 5 / 5 Регистрация: 16.12.2013 Сообщений: 463 |
||||
28.10.2014, 18:43 |
5 |
|||
Прогу не компилировала,но вроде ничего не упустила. Там стоит обратить внимание на то,что корень вычисляется только с неотрицательных чисел
1 |
73 / 73 / 28 Регистрация: 06.10.2013 Сообщений: 309 |
|
28.10.2014, 18:45 |
6 |
Прогу не компилировала оно и видно) для cin и cout нужна iostream, которой нет)
0 |
5 / 5 / 5 Регистрация: 16.12.2013 Сообщений: 463 |
|
28.10.2014, 18:46 |
7 |
О да,самое главное)))
0 |
BeyB 0 / 0 / 0 Регистрация: 28.10.2014 Сообщений: 23 |
||||
28.10.2014, 19:03 [ТС] |
8 |
|||
спасибо успел сделать всё кажется пол часа назад , спасибо большое за то что предупредили что мой первый код было магко говоря бесполезным
0 |
zss Модератор 12641 / 10135 / 6102 Регистрация: 18.12.2011 Сообщений: 27,170 |
||||
28.10.2014, 19:09 |
9 |
|||
Сообщение было отмечено BeyB как решение Решение
1 |
Содержание
- Ошибка компилятора C2059
- Name already in use
- cpp-docs / docs / error-messages / compiler-errors-1 / compiler-error-c2059.md
- Error c2059 syntax error declspec dllexport
- Лучший отвечающий
- Вопрос
- Ответы
- Error c2059 syntax error declspec dllexport
- Answered by:
- Question
- Answers
- All replies
Ошибка компилятора C2059
Синтаксическая ошибка: «token»
Маркер привел к синтаксической ошибке.
В следующем примере создается сообщение об ошибке для строки, которая объявляется j .
Чтобы определить причину ошибки, проверьте не только строку, указанную в сообщении об ошибке, но и строки над ней. Если проверка строк не дает каких либо сведений о проблеме, попробуйте закомментировать строку, указанную в сообщении об ошибке, и, возможно, несколько строк выше.
Если сообщение об ошибке возникает в символе, который сразу же следует за typedef переменной, убедитесь, что переменная определена в исходном коде.
C2059 возникает, когда имя символа препроцессора повторно используется в качестве идентификатора. В следующем примере компилятор видит DIGITS.ONE как число 1, которое недопустимо в качестве имени элемента enum:
Вы можете получить C2059, если символ равен Nothing, как это может произойти, если для компиляции используетсясимвол=/d.
Еще один случай, когда может произойти C2059, — при компиляции приложения, которое указывает структуру в аргументах по умолчанию для функции. Значение аргумента по умолчанию должно быть выражением. Список инициализаторов, например тот, который использовался для инициализации структуры, не является выражением. Чтобы устранить эту проблему, определите конструктор для выполнения необходимой инициализации.
Следующий пример приводит к возникновению ошибки C2059:
C2059 может возникать при неправильном приведении.
Следующий пример приводит к возникновению ошибки C2059:
C2059 также может возникнуть при попытке создать имя пространства имен, содержащее точку.
Следующий пример приводит к возникновению ошибки C2059:
C2059 может возникать, если за оператором, который может квалифицироваться имя ( :: , -> и . ), должно следовать ключевое слово template , как показано в следующем примере:
По умолчанию в C++ предполагается, что AY::Rebind он не является шаблоном, поэтому следующий пример интерпретируется как знак «меньше». Необходимо явно сообщить компилятору, что Rebind является шаблоном, чтобы он мог правильно проанализировать угловую скобку. Чтобы исправить эту ошибку, используйте template ключевое слово в имени зависимого типа, как показано ниже:
Источник
Name already in use
cpp-docs / docs / error-messages / compiler-errors-1 / compiler-error-c2059.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
Copy raw contents
Copy raw contents
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 .
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:
You may get C2059 if a symbol evaluates to nothing, as can occur when /Dsymbol= is used to compile.
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:
C2059 can occur for an ill-formed cast.
The following sample generates C2059:
C2059 can also occur if you attempt to create a namespace name that contains a period.
The following sample generates C2059:
C2059 can occur when an operator that can qualify a name ( :: , -> , and . ) must be followed by the keyword template , as shown in this example:
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:
Источник
Error c2059 syntax error declspec dllexport
Лучший отвечающий
Вопрос
I’m migrating a Win 32 project written in Visual C++ 5.0 to Visual Studio 2012. I get the below error message on building the application.
Error C2059: syntax error : ‘_ declspec(dllexport)’
Clicking on the Error messages it points to the code highlighted in bold.
The above error message repeats for all the code in bold. I could not understand where the error is, could anyone help me to fix this error, it does not look like a syntax error though. Is it a migration error, as the same set of code works fine in vc++ 5.0 without any issues?
I also get the following Errors along with the above mentioned error:
Error C2143: syntax error: missing ‘;’ before ‘<‘
Clicking on the error, it points to the following code. (get_Path is one of the utility functions mentioned in the code snippet above)
/* The following two function sets and gets the path*/
char* EXPORT_FN Get_Path(void) <
Thanks for any help!
Ответы
On 5/7/2013 4:13 AM, suj1234 wrote:
#ifdef __EXPORTING
#define EXPORT_FN __declspec (dllexport) WINAPI
#define C_EXPORT_FN __declspec (dllexport) _cdecl
#else
#define EXPORT_FN __declspec (dllimport) WINAPI
#define C_EXPORT_FN __declspec (dllimport) _cdecl
#endif
char* EXPORT_FN Get_LogFile(void);
The syntax doesn’t allow __declspec where you have it (see http://msdn.microsoft.com/en-us/library/dabb5z75.aspx , second example from the bottom). It should be one of
Only the last version works if you want to keep __declspec and __stdcall (or __cdecl) together. Normally, they are separated into individual macros. For example, this is the declaration in a Windows header:
WINBASEAPI is a macro that expands to __declspec(dllimport) or nothing (and, presumably, to __declspec(dllexport) in the configuration used to actually build Windows from sources), while WINAPI expands to __stdcall. One goes before the return type, the other after.
Источник
Error c2059 syntax error declspec dllexport
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I want to write a native C++ function that I can later access from C#.
Please keep in mind I do not have much experience developing on windows, (mostly unix) and that my only windows compiler is VS2005.
I tried creating a MFC DLL. I am able to access this from a C++ .net program, but not from a C# program using P/Invoke. It seems that a plain MFC DLL is not «good enough» for use with DllImport. Is this correct?
It seems that I have two options:
1) compile the C++ function as a COM DLL (not sure how to do this from VS2005 — I don’t see an option for that). I see an option for an ActiveX DLL. I hope I don’t need to do that.
2) write a C++ .net wrapper class, create a .net assembly, and use that assembly from C#.
I would prefer option 1. how do I create a DLL that C# can use via [DllImport] ?
Answers
You are confusing Platform/Invoke with COM interop. These are two separate interop techniques. As far as which one you should use I would lean toward PInvoke given your newness to Windows programming. PInvoke meets most needs and is simple to use.
For PInvoke all you need is the C signature for a method to call in a DLL. If you want to write your code in C++ then you must: a) create a static or global function in C++ (no class methods), and b) you must mark the function with extern «C» in order to change the namemangling from C++ to C. You can not access C++ classes or class members through PInvoke. Theoretically you can but honestly it is simply too difficult and not worth the effort.
Here is a function you might write in C++:
//In DLL: MyDll.dll
extern «C» double SquareRoot ( double value )
<
//Do work
>
In C# you would do this:
public class MyClass
<
public double SqrRoot ( double value )
<
return SquareRoot(value);
>
[DllImport(«MyDll.dll»)]
private static extern double SquareRoot ( double value );
>
The general rule of thumb is to make these functions private and put a .NET wrapper around it like in the example. DllImport accepts a lot of optional parameter to control character sets, error handling, etc. Furthermore each parameter can be attributed to control marshaling and whatnot but the above example gives you the basics.
If you want to expose an entire class and its methods then you are forced to use COM interop. This requires that you create a COM interface and class using ATL or something and then register the COM object. You then have to import the COM object into a .NET project (or use tlbimp) to generate the COM proxy that .NET will use. You can then use the auto-generated proxy to talk with the COM object. However I’d avoid this if at all possible since it complicates issues and adds to deployment requirements. For more information use MSDN to look up Platform/Invoke and COM Interop.
Michael Taylor — 6/13/06
You are confusing Platform/Invoke with COM interop. These are two separate interop techniques. As far as which one you should use I would lean toward PInvoke given your newness to Windows programming. PInvoke meets most needs and is simple to use.
For PInvoke all you need is the C signature for a method to call in a DLL. If you want to write your code in C++ then you must: a) create a static or global function in C++ (no class methods), and b) you must mark the function with extern «C» in order to change the namemangling from C++ to C. You can not access C++ classes or class members through PInvoke. Theoretically you can but honestly it is simply too difficult and not worth the effort.
Here is a function you might write in C++:
//In DLL: MyDll.dll
extern «C» double SquareRoot ( double value )
<
//Do work
>
In C# you would do this:
public class MyClass
<
public double SqrRoot ( double value )
<
return SquareRoot(value);
>
[DllImport(«MyDll.dll»)]
private static extern double SquareRoot ( double value );
>
The general rule of thumb is to make these functions private and put a .NET wrapper around it like in the example. DllImport accepts a lot of optional parameter to control character sets, error handling, etc. Furthermore each parameter can be attributed to control marshaling and whatnot but the above example gives you the basics.
If you want to expose an entire class and its methods then you are forced to use COM interop. This requires that you create a COM interface and class using ATL or something and then register the COM object. You then have to import the COM object into a .NET project (or use tlbimp) to generate the COM proxy that .NET will use. You can then use the auto-generated proxy to talk with the COM object. However I’d avoid this if at all possible since it complicates issues and adds to deployment requirements. For more information use MSDN to look up Platform/Invoke and COM Interop.
Michael Taylor — 6/13/06
I finally got this to work, but there are some critical steps that have not been mentioned. I will document them in case someone else has the same problem.
First, create the native win32 dll using VS2005:
Create a C++ win32 project. (I called my project «MyWin32Function»). In the wizard, set application type to «DLL». Check the «export symbols» box.
This creates a template file «MyWin32Function.cpp». The template contains an example function, class, and variable to be exported. I deleted the variable and the class. I modified the function to extern «C» and wrote code to simply multiply two floats.
The other important thing in the template (which nobody mentions) is the DllMain at the top. Frankly, I have no idea what that is (I come from a unix background) but it seems to be necessary if you want to link to the dll from another program.
Here is the complete MyWin32Function.cpp:
// MyWin32Function.cpp : Defines the entry point for the DLL application.
//
#include «stdafx.h»
#include «MyWin32Function.h»
#ifdef _MANAGED
#pragma managed(push, off)
#endif
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
<
switch (ul_reason_for_call)
<
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
>
return TRUE;
>
#ifdef _MANAGED
#pragma managed(pop)
#endif
// This is an example of an exported function.
extern «C» MYWIN32FUNCTION_API float fnMyWin32Function(float a,float b)
<
return a*b;
>
I then compiled the file and copied the resulting dll to a directory in my PATH.
The C# side is now fairly easy. I created a C# console project. I did not need to modify any of the default project properties. However, you do need the using Sytem.Runtime.InteropServices! Here is the complete C# file:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace MyCsharpTest
<
class Program
<
[DllImport(«MyWin32Function.dll»)]
private static extern Single fnMyWin32Function(Single a, Single b);
static void Main(string[] args)
<
Single a = 10.0f;
Single b = 20.0f;
Single c = fnMyWin32Function(a,b);
System.Console.WriteLine(c);
>
>
>
Hopefully this is useful to someone else.
DllMain is not needed in order to export functions. DllMain is a helper routine that DLLs can implement to be notified when they are loaded and unloaded in the process and for each thread. This function is normally used to initialize global variables or run global functions prior to the DLL being used. DllMain is called by Windows after the DLL is loaded but before control returns to the loader (technically the function called is an RTL function that initializes the C++ library and then calls DllMain). The problem with DllMain is the fact that it is loaded within a synchronization block that the loader uses (at least it use to be, not sure whether this is still true in XP) so there are certain things that can’t be done within DllMain.
Most DLLs implement this function simply because each time you create a thread or a thread terminates every DLL loaded in the process has its DllMain called with the appropriate reason code. This is wasteful if the DLL doesn’t care about threads (the general case). Therefore the defacto implementation of this function looks like this:
BOOL WINAPI DllMain ( HMODULE hModule, DWORD dwReason, LPVOID reserved )
<
switch(dwReason)
<
case DLL_PROCESS_ATTACH :
case DLL_PROCESS_DETACH :
case DLL_THREAD_DETACH : break;
case DLL_THREAD_ATTACH :
<
//Disable thread notifications
DisableThreadLibraryCalls(hModule);
>;
>;
>
The other important use of this function is to get the HMODULE for the DLL which you need for some API calls. Note that some frameworks like MFC and ATL use DllMain to perform framework initialization as well.
Источник
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).
- Remove From My Forums
-
Question
-
struct A { int i; A() {} A(int i) : i(i) {} }; template <typename T> struct Help { typedef A B; }; template <typename T2> int foo(T2 t2, typename Help<T2>::B b = typename Help<T2>::B(0)) { return 0; } int main() { int I; int res = foo(I); return res; } /* $ cl.exe C2059.cpp Microsoft (R) C/C++ Optimizing Compiler Version 19.15.26729 for x64 Copyright (C) Microsoft Corporation. All rights reserved. C2059.cpp C2059.cpp(22): error C2059: syntax error: '' C2059.cpp(31): fatal error C1903: unable to recover from previous error(s); stopping compilation */
-
Edited by
Thursday, September 20, 2018 1:00 PM
add a line so that error message matches
-
Edited by
Problem
The Microsoft C/C++ compiler might throw this error, when the code contains an IBM Rational Test RealTime Code Review pragma. This technote proposes a workaround.
Symptom
The error message is as follows:
error C2059: syntax error : 'bad suffix on number'
Cause
See the following code.
#pragma attol crc_justify (Rule M1.1w, "Rule M1.1w : This rule is acceptable on the next line")
The Microsoft Visual C/C++ compiler reports the error on this line.
The Microsoft Visual C/C++ compiler interprets the first parameter of the
crc_justify
pragma,
Rule M1.1w
, as a number. However the suffix
w
is not an allowed suffix for a number. This is not a defect in the implementation of the pragmas. The ANSI C standard states, that compilers should ignore pragmas, that they do not understand.
Resolving The Problem
To workaround the problem you use the alternate name of the rule as the first parameter to the crc_justify pragma.
Open your project’s
confrule.xml
file in a text editor. You can find the path to this file in the settings dialog box, section Code Review > Rule Configuration.
If you see the string default, open the file in the IBM Rational Test RealTime installation directory. For example:
C:Program FilesRationalTestRealTimepluginsCommonlibconfrule.xml
In this file you see the following line near the beginning:
<rule name=»CRC_10_11″ label=»Rule M1.1w» severity=»2″ repeat=»0″ errMsg=»ANSI C warning: %name%» />
The n
ame
attribute gives the internal name for the rule. The
label
attribute gives the external name for the rule. You can use either the internal or the external name in the
crc_justify
pragma.
Therefore to workaround this problem, you change your pragma to become:
#pragma attol crc_justify (CRC_10_11, "Rule M1.1w : This rule is acceptable on the next line")
[{«Product»:{«code»:»SSSHUF»,»label»:»Rational Test RealTime»},»Business Unit»:{«code»:»BU053″,»label»:»Cloud & Data Platform»},»Component»:»Code Review for C»,»Platform»:[{«code»:»PF002″,»label»:»AIX»},{«code»:»PF010″,»label»:»HP-UX»},{«code»:»PF016″,»label»:»Linux»},{«code»:»PF027″,»label»:»Solaris»},{«code»:»PF033″,»label»:»Windows»}],»Version»:»7.0;7.0.0.1;7.0.5;7.0.5.1;7.5″,»Edition»:»»,»Line of Business»:{«code»:»LOB45″,»label»:»Automation»}}]
Product Synonym
testrt;rtrt