Main cs 2 0 error cs1024 wrong preprocessor directive

C# Preprocessor bug?; found in VS2017 (15.7.2) #27109 Comments The code below gives the following compilation error: error CS1024: Preprocessor directive expected The strange part is that it ONLY happens when the code is part of a #if/#endif block that is NOT defined. This seems like a bug. The text was updated successfully, but […]

Содержание

  1. C# Preprocessor bug?; found in VS2017 (15.7.2) #27109
  2. Comments
  3. #if preprocessor directive incorrectly handles enclosed C# verbatim string #4726
  4. Comments
  5. Main cs 2 0 error cs1024 wrong preprocessor directive

C# Preprocessor bug?; found in VS2017 (15.7.2) #27109

The code below gives the following compilation error:

error CS1024: Preprocessor directive expected

The strange part is that it ONLY happens when the code is part of a #if/#endif block that is NOT defined.

This seems like a bug.

The text was updated successfully, but these errors were encountered:

This is not a bug and is very much the design of C# since v1. 🙂

When _THIS_IS_NOT_DEFINED_ is not defined, then the compiler gets to the #if , sees that the condition is false, and considers all text up to the next preprocessor directive (like #else , #elif or #endif ) as ‘disabled text’. In this case, this means it just consumes the code blindly as text until it sees teh # in #rates . There, it says «aha, what sort of directive do i have? ‘rates’?? that’s not a thing. ERROR!».

The difference here is that when the scanner is dealing with ‘disabled text’ sections, it’s not going and making tokens like the normal scanning does. So it has no concept that @» is special and starts some sort of string. Instead, it just does not give a hoot.

** This is important as you want people to put any code they want into a verbatim string (except a quote) and not have the compiler ‘interpret’ it in any fashion. Otherwise, you’d have to escape your pp-directives in a string, which would defeat the purpose of it being a ‘verbatim’ string. 🙂

Thanks for the detail explanation. It does feel odd that valid code can start to fail if wrapped in an undefined preprocessor block in this way; however, it is certainly easy to work around. Should the scanning of disabled text take into account the @» text as a future improvement to the C# preprocessor? I’m just curious on your take.

text take into account the @» text as a future improvement to the C# preprocessor? I’m just curious on your take.

Unfortunately, that can’t happen, it would be a breaking change. There is code out there that def depends on this behavior. :-/

Maybe it would make sense to ignore unknown preprocessor directives in disabled sections of code? I think that wouldn’t be a breaking change.

Источник

#if preprocessor directive incorrectly handles enclosed C# verbatim string #4726

To reproduce, just use this code and make sure that DEBUG is set:

Actually, this produces a CS1024 error because the compiler seems to interpret the «# text» portion of the string as a preprocessor directive.

The text was updated successfully, but these errors were encountered:

I’m pretty sure this is by design. Once the compiler sees the #if !DEBUG it’s going to be in an inactive region. Once in that state it will continue scanning through the inactive region handling other preprocessor directives, until it finally ends that region (with the #endif ). Inside that region, the compiler has no concept of things a multi-line string literal.

We should investigate whether this is a bug or per spec.

From my reading, this is ‘per spec’. The relevant sections are:

Because ‘DEBUG’ is defined, then the pp-expression evaluates to false , meaning we’ll be in a skipped-section .

The spec then says:

The remaining conditional-sections, if any, are processed as skipped-sections: except for pre-processing directives, the source code in the section need not adhere to the lexical grammar; no tokens are generated from the source code in the section; and pre-processing directives in the section must be lexically correct but are not otherwise processed.

As such, it is ‘per spec’ that an error is produced as the compiler is checking that the #text «pre-processing directives in the section must be lexically correct». As #text is not a legal pp-directive, the error is appropriate.

Fair enough; per the spec I agree that this can’t be considered a bug. Nonetheless it is rather unintuitive behavior — requiring pre-processing directives to be «lexically correct» while declaring that they are unprocessed goes contrary to what one would expect — that everything is skipped until the #endif directive is encountered at the beginning of a line. Sounds like my problem is actually with the spec and not the implementation 🙂

All that being said, this was a rather odd scenario that popped up and was easy to work around. Thanks for looking into it.

When commenting out a block of code, I recommend using line-ending comments. In VS, select the code to be commented out and hit control-K control-C. To uncomment a block of code select it and hit control-K control-U.

I acknowledge that this doesn’t help in your scenario, where you want the code commented or not depending on a PP-symbol.

Agreed on the line-ending comments; I’m a big fan of ctrl-K,C. This was literally a case of production code having a C# verbatim string inside a skipped block with a line that happened to begin with #. I can’t imagine that this is a very common use case, but I wanted to at least report this behavior in case it wasn’t intended. Again, thanks for taking the time to check this out and explain it to me.

I think it’s so you don’t end up accident writing something like:

in the middle of your skipped section. With the current spec approach, you’ll get a nice error here and you can fix the directive.

From: gdivismailto:notifications@github.com
Sent: ‎8/‎24/‎2015 10:21 AM
To: dotnet/roslynmailto:roslyn@noreply.github.com
Cc: Cyrus Najmabadimailto:cyrusn@microsoft.com
Subject: Re: [roslyn] #if preprocessor directive incorrectly handles enclosed C# verbatim string (#4726)

Fair enough; per the spec I agree that this can’t be considered a bug. Nonetheless it is rather unintuitive behavior — requiring pre-processing directives to be «lexically correct» while declaring that they are unprocessed goes contrary to what one would expect — that everything is skipped until the #endif directive is encountered at the beginning of a line. Sounds like my problem is actually with the spec and not the implementation 🙂

All that being said, this was a rather odd scenario that popped up and was easy to work around. Thanks for looking into it.

Источник

Main cs 2 0 error cs1024 wrong preprocessor directive

В стандарте написано следующее:

9.5.4 Conditional compilation directives
.
The remaining conditional-sections, if any, are processed as skipped-sections: except for pre-processing
directives, the source code in the section need not adhere to the lexical grammar; no tokens are generated
from the source code in the section; and pre-processing directives in the section shall be lexically correct but
are not otherwise processed
.

От: Ovl
Дата: 01.06.07 14:01
Оценка:

N>9.5.4 Conditional compilation directives
N>.
N>The remaining conditional-sections, if any, are processed as skipped-sections: except for pre-processing
N>directives, the source code in the section need not adhere to the lexical grammar; no tokens are generated
N>from the source code in the section; and pre-processing directives in the section shall be lexically correct but
N>are not otherwise processed.

От: Ovl
Дата: 01.06.07 14:02
Оценка:
От: Ovl
Дата: 01.06.07 14:06
Оценка:

Здравствуйте, Ovl, Вы писали:

Ovl>хотя да, даже валидный #if не пропускается. странные коментарии в с#

а, ну да. он же не валиден

вот так все в порядке

От: lonli
Дата: 01.06.07 14:59
Оценка:

Здравствуйте, nikov, Вы писали:

Да забей ты

«Чтобы все знать интернет нафик не нужен! НУжен утюг!» ©сб. БГУ

От: Алексей.
Дата: 04.06.07 07:58
Оценка:

N>9.5.4 Conditional compilation directives
N>.
N>The remaining conditional-sections, if any, are processed as skipped-sections: except for pre-processing
N>directives, the source code in the section need not adhere to the lexical grammar; no tokens are generated
N>from the source code in the section; and pre-processing directives in the section shall be lexically correct but
N>are not otherwise processed
.

От: nikov http://www.linkedin.com/in/nikov
Дата: 04.06.07 08:03
Оценка:

Здравствуйте, Алексей., Вы писали:

А>Компилятор в данном случае соотвествует стандарту. Многострочный комментарий, тот что со звездочками, не имеет эффект в skipped-секциях и обрабатывается как последовательность входных символов, а не как единый токен-комментарий. Поэтому когда компилятор встречает #bugaga внутри skipped-секции он его пытается обработать как директиву препроцессора.

Про комментарии я понимаю. Но в стандарте написано, что директивы препроцессора в skipped-секции не обрабатываются, если они не являются лексически корректными. Иначе получилось бы, что текст внутри skipped-секции, случайно начинающийся с #, будет вызывать ошибку (что мы и наблюдаем).

От: Алексей.
Дата: 04.06.07 08:19
Оценка:

Здравствуйте, nikov, Вы писали:

N>Про комментарии я понимаю. Но в стандарте написано, что директивы препроцессора в skipped-секции не обрабатываются, если они не являются лексически корректными. Иначе получилось бы, что текст внутри skipped-секции, случайно начинающийся с #, будет вызывать ошибку (что мы и наблюдаем).

Хм. Похоже ты прав. Невнимательно я прочитал выделенную фразу.

От: Ovl
Дата: 04.06.07 08:32
Оценка:

Здравствуйте, nikov, Вы писали:

N>Здравствуйте, Алексей., Вы писали:

А>>Компилятор в данном случае соотвествует стандарту. Многострочный комментарий, тот что со звездочками, не имеет эффект в skipped-секциях и обрабатывается как последовательность входных символов, а не как единый токен-комментарий. Поэтому когда компилятор встречает #bugaga внутри skipped-секции он его пытается обработать как директиву препроцессора.

N>Про комментарии я понимаю. Но в стандарте написано, что директивы препроцессора в skipped-секции не обрабатываются, если они не являются лексически корректными. Иначе получилось бы, что текст внутри skipped-секции, случайно начинающийся с #, будет вызывать ошибку (что мы и наблюдаем).

простите, а как вы перевели фразу?

except for pre-processing directives, the source code in the section need not adhere to the lexical grammar

and pre-processing directives in the section shall be lexically correct but are not otherwise processed

От: nikov http://www.linkedin.com/in/nikov
Дата: 04.06.07 09:44
Оценка: -1

except for pre-processing directives, the source code in the section need not adhere to the lexical grammar

код в этой секции, за исключением директив препроцессора, не обязан придерживаться [правил] грамматики

and pre-processing dirctives in the section shall be lexically correct but are not otherwise processed

директивам препроцессора в этой секции следует быть лексически правильными, иначе они не будут обработаны

От: Ovl
Дата: 04.06.07 09:46
Оценка: 23 (2)

except for pre-processing directives, the source code in the section need not adhere to the lexical grammar

код в этой секции, за исключением директив препроцессора, не обязан придерживаться [правил] грамматики

and pre-processing dirctives in the section shall be lexically correct but are not otherwise processed

директивам препроцессора в этой секции следует быть лексически правильными, иначе они не будут обработаны

От: nikov http://www.linkedin.com/in/nikov
Дата: 04.06.07 09:50
Оценка:

директивам препроцессора в этой секции следует быть лексически правильными, иначе они не будут обработаны

Ovl>директивам препроцессора в этой секции следует быть лексически правильными, кроме этого они никак не обработываются

Спасибо, я согласен. Мой перевод был неверным.
Однако, #bugaga — это не директива препроцессора, и она не обязана быть лексически правильной.

От: Ovl
Дата: 04.06.07 09:53
Оценка:

N>Однако, #bugaga — это не директива препроцессора, и она не обязана быть лексически правильной.

директива — это последовательность # если перед ним до начала строки ничего нет

От: nikov http://www.linkedin.com/in/nikov
Дата: 04.06.07 09:55
Оценка:

Здравствуйте, Ovl, Вы писали:

N>>Однако, #bugaga — это не директива препроцессора, и она не обязана быть лексически правильной.

Ovl>директива — это последовательность # если перед ним до начала строки ничего нет

Откуда это следует?
Я ориентируюсь на следующее определение:

От: Алексей.
Дата: 04.06.07 10:00
Оценка:

and pre-processing dirctives in the section shall be lexically correct but are not otherwise processed

директивам препроцессора в этой секции следует быть лексически правильными, иначе они не будут обработаны

Ovl>директивам препроцессора в этой секции следует быть лексически правильными, кроме этого они никак не обработываются

Спасибо за перевод. Значит компилятор и я все-таки правы.

От: nikov http://www.linkedin.com/in/nikov
Дата: 04.06.07 10:09
Оценка:

Здравствуйте, Ovl, Вы писали:

Ovl>директива — это последовательность # если перед ним до начала строки ничего нет

Компилятор выдает ошибку и на таком коде:

, где никакого слова нет.

От: Ovl
Дата: 04.06.07 10:12
Оценка:

Здравствуйте, nikov, Вы писали:

N>Здравствуйте, Ovl, Вы писали:

N>>>Однако, #bugaga — это не директива препроцессора, и она не обязана быть лексически правильной.

Ovl>>директива — это последовательность # если перед ним до начала строки ничего нет

N>Откуда это следует?
N>Я ориентируюсь на следующее определение:

N>

верно. это правильные директивы.
а списка неправильных там разве не приведено?

A pre-processing directive always occupies a separate line of source code and always begins
with a # character and a pre-processing directive name. White space may occur before the # character
and between the # character and the directive name.

От: nikov http://www.linkedin.com/in/nikov
Дата: 04.06.07 10:14
Оценка:

Ovl>A pre-processing directive always occupies a separate line of source code and always begins
Ovl>with a # character and a pre-processing directive name. White space may occur before the # character
Ovl>and between the # character and the directive name.

От: Ovl
Дата: 04.06.07 10:19
Оценка:

Здравствуйте, nikov, Вы писали:

N>Здравствуйте, Ovl, Вы писали:

Ovl>>директива — это последовательность # если перед ним до начала строки ничего нет

N>Компилятор выдает ошибку и на таком коде:

N>
N>, где никакого слова нет.

нету. об этом вам компилятор и говорит. что-нибудь типа «directive expected»

От: nikov http://www.linkedin.com/in/nikov
Дата: 04.06.07 11:02
Оценка:

Здравствуйте, Ovl, Вы писали:

Ovl>нету. об этом вам компилятор и говорит. что-нибудь типа «directive expected»

В общем, ситуация понятна. Если внутри skipped-секции встречается строка, первый непробельный символ в которой — #, то эта строка должна содержать корректную директиву препроцессора, иначе возникает ошибка компиляции. Я бы не сказал, что эта мысль ясно выражена в стандарте.

Источник

@gdivis commented on Fri Aug 21 2015

To reproduce, just use this code and make sure that DEBUG is set:

#if !DEBUG
    [Description(@"
    # text")]
    class Test
    {
    }
#endif

Actually, this produces a CS1024 error because the compiler seems to interpret the «# text» portion of the string as a preprocessor directive.


@CyrusNajmabadi commented on Fri Aug 21 2015

I’m pretty sure this is by design. Once the compiler sees the #if !DEBUG it’s going to be in an inactive region. Once in that state it will continue scanning through the inactive region handling other preprocessor directives, until it finally ends that region (with the #endif). Inside that region, the compiler has no concept of things a multi-line string literal.


@gafter commented on Sun Aug 23 2015

We should investigate whether this is a bug or per spec.


@CyrusNajmabadi commented on Sun Aug 23 2015

From my reading, this is ‘per spec’. The relevant sections are:

pp-if-section:
    whitespaceopt  #  whitespaceopt  if  whitespace  pp-expression  pp-new-line  conditional-sectionopt

conditional-section:
    input-section
    skipped-section

Because ‘DEBUG’ is defined, then the pp-expression evaluates to false, meaning we’ll be in a skipped-section.

The spec then says:

The remaining conditional-sections, if any, are processed as skipped-sections: except for pre-processing directives, the source code in the section need not adhere to the lexical grammar; no tokens are generated from the source code in the section; and pre-processing directives in the section must be lexically correct but are not otherwise processed.

As such, it is ‘per spec’ that an error is produced as the compiler is checking that the #text «pre-processing directives in the section must be lexically correct». As #text is not a legal pp-directive, the error is appropriate.


@gdivis commented on Mon Aug 24 2015

Fair enough; per the spec I agree that this can’t be considered a bug. Nonetheless it is rather unintuitive behavior — requiring pre-processing directives to be «lexically correct» while declaring that they are unprocessed goes contrary to what one would expect — that everything is skipped until the #endif directive is encountered at the beginning of a line. Sounds like my problem is actually with the spec and not the implementation :)

All that being said, this was a rather odd scenario that popped up and was easy to work around. Thanks for looking into it.


@gafter commented on Mon Aug 24 2015

When commenting out a block of code, I recommend using line-ending comments. In VS, select the code to be commented out and hit control-K control-C. To uncomment a block of code select it and hit control-K control-U.

I acknowledge that this doesn’t help in your scenario, where you want the code commented or not depending on a PP-symbol.


@gdivis commented on Mon Aug 24 2015

Agreed on the line-ending comments; I’m a big fan of ctrl-K,C. This was literally a case of production code having a C# verbatim string inside a skipped block with a line that happened to begin with #. I can’t imagine that this is a very common use case, but I wanted to at least report this behavior in case it wasn’t intended. Again, thanks for taking the time to check this out and explain it to me.


@CyrusNajmabadi commented on Mon Aug 24 2015

I think it’s so you don’t end up accident writing something like:

#els

in the middle of your skipped section. With the current spec approach, you’ll get a nice error here and you can fix the directive.


From: gdivismailto:notifications@github.com
Sent: ‎8/‎24/‎2015 10:21 AM
To: dotnet/roslynmailto:roslyn@noreply.github.com
Cc: Cyrus Najmabadimailto:cyrusn@microsoft.com
Subject: Re: [roslyn] #if preprocessor directive incorrectly handles enclosed C# verbatim string (#4726)

Fair enough; per the spec I agree that this can’t be considered a bug. Nonetheless it is rather unintuitive behavior — requiring pre-processing directives to be «lexically correct» while declaring that they are unprocessed goes contrary to what one would expect — that everything is skipped until the #endif directive is encountered at the beginning of a line. Sounds like my problem is actually with the spec and not the implementation :)

All that being said, this was a rather odd scenario that popped up and was easy to work around. Thanks for looking into it.


Reply to this email directly or view it on GitHubhttps://na01.safelinks.protection.outlook.com/?url=https%3a%2f%2fgithub.com%2fdotnet%2froslyn%2fissues%2f4726%23issuecomment-134306795&data=01%7c01%7ccyrusn%40microsoft.com%7c3193db7629df45631f8708d2aca87b02%7c72f988bf86f141af91ab2d7cd011db47%7c1&sdata=WtqC2fjQ9vwmrBR%2fahpVbLhdxiJ%2fGUWeS1eqW%2fANQ9w%3d.


@DiryBoy commented on Tue Aug 25 2015

This is similar to

Ops


@NickCraver commented on Mon Nov 02 2015

Can we open this back up to see if it should be «by-design» (on the spec side)? This bit us when building Stack Overflow when a debug section had some markdown inside a string. I don’t really think markdown in a string is insanely uncommon — I’d imagine quite a few people will hit this over time for that and other use cases…and it’s not at all intuitive as to why Roslyn suddenly breaks here.


@CyrusNajmabadi commented on Mon Nov 02 2015

@NickCraver

and it’s not at all intuitive as to why Roslyn suddenly breaks here.

Could you explain what you mean by this? It sounds like you’re saying one of two things here:

  1. It’s not intuitive why Roslyn breaks versus the pre-Roslyn compiler.
  2. It’s not intuitive why C# has this behavior at all.

If the former, this should not be the case. We should have the same behavior as the pre-Roslyn compiler.

If the latter… well, it’s in the eye of the beholder. It’s intuitive for me. The compiler is in preprocessor-translation mode. And it sees an invalid preprocessor directive. So it dies. Makes sense to me :)


@svick commented on Tue Nov 03 2015

@CyrusNajmabadi I’m not sure «is intuitive to compiler implementer» is the right goal. I think that normal developers are not going to think like that.

To me the intuitive behavior is «surrounding any piece of code with #if will just work». Maybe it’s not possible to reach that (e.g. what if there’s #endif inside the string literal?), but getting closer sounds like a worthwhile goal to me.


@NickCraver commented on Tue Nov 03 2015

Sorry, busy days here lately :) It’s definitely the latter — surrounding a chunk of code with #if <directive>/#endif for example should just work. Most developers won’t understand why this broke without digging a little.

This gets further complicated in our case because we do compile-time replacement of strings for localization. That wasn’t the case hit here (it was simple markdown), but the fact that a string our translators give us can just break builds one day is a little scary. I simply think we can do better here.


@CyrusNajmabadi commented on Tue Nov 03 2015

It would be unintuitive to me to try to understand why a #elseif was not working. Today the compiler will helpfully tell me that #elseif is wrong (and I should use #elif instead).

Either way has pros and cons. The current approach has the benefit of telling when I do things wrong, but impeding you if you use pp directives in multi-line string literals. The approach you suggest allows for multi-line string literals, but means I don’t get good feedback about when i’m doing things wrong.


@gafter commented on Tue Nov 03 2015

@NickCraver Do you have a specific proposal for changes to the language specification? Absent a proposed alternative, I don’t see what the value would be in reopening the issue. The current spec and all implementations agree, and we would not be likely to take a change that could break existing programs.


@NickCraver commented on Tue Nov 03 2015

@CyrusNajmabadi Indeed, that’s not the error we’re talking about here though. Any multi-line string that has a line starting with # will result in this:

error CS1024: Preprocessor directive expected

That’s far less intuitive than information errors from actually using a directive incorrectly. The surface area for hitting such a thing is much larger. In our case it’s markdown, for others it may be a PowerShell comment, etc. I’m not sure how excluding multi-line strings (which admittedly may be very non-trivial) would prevent your case of good informational errors with misused directives. I think the problem here is identifying what is a directive, a step before that.


@DiryBoy commented on Tue Nov 03 2015

If verbatim strings are accounted for, what about normal and interpolated strings? What about multiline comments?

It isn’t uncommon to have s = "@"; or other kinds of commented codes that confuses the «degraded parser» which only account for multiline strings right?


@agocke commented on Tue Nov 03 2015

@NickCraver @DiryBoy Let’s be clear here — there is no source code inside inactive #if directives. Nothing is parsed, compiled, analyzed — anything. Excluding strings inside directives has no meaning because there’s no such thing as a string, just a block of text that may or may not contain preprocessor directives.

I think any proposal needs to start from there and any assumptions it implies, including that people could have entire files containing inactive #if blocks consisting of nothing but kilobytes of line noise.


@paul1956 commented on Tue Nov 03 2015

VB seems to require the # start in the first column (at least by default it auto formats it that way removing all the whitespace), but then as @agocke says the false clause is just a blob of text. What seems confusing to me is if I change True to False then the error appears at the #Else instead of the #End If. Since you are forced to have the # as the first character of the line why not change the grammar to require it and then most/all of the issues with # appearing in strings goes away except when the # is the first character. Alternatively there should be some kind of escape for # that allows it to be ignored when on the false side and treated as a # when on the true side. If I have to edit one side or the other every time the condition changes the preprocessor directive is less useful. There could then be a Analyzer and Fix to detect and fix these corner cases.

#If TRUE Then
        Dim x As String = "
         #End If"
#Else
        Dim x As String = "
#End If"
#End If ' Error here because previous part of line is taken as a Preprocessor string 

@gafter commented on Tue Nov 03 2015

If the # were «ignored» in the false side, how would the false side ever end?


@agocke commented on Tue Nov 03 2015

Since you are forced to have the # as the first character of the line

C# Spec Section 2.5:

White space may occur before the # character and between the # character and the directive name.


@paul1956 commented on Tue Nov 03 2015

@gagter I was proposing the use of an escape character before the # so that it could be ignored in the cases sited.

@agocke I was talking about VB which has the same issues and Visual Studio removes any leading white space so it ignored the spec assuming it shares that grammar with C#.


@agocke commented on Tue Nov 03 2015

@paul1956 Pick any escape character you want that’s not whitespace. As long as there is a non-whitespace character before # it isn’t regarded as the start of a directive.


@paul1956 commented on Tue Nov 03 2015

@agocke how does that help. The compiler doesn’t understand it. I would have to remove it every time the condition changed.
In the True clause I need # and in the False clause I need escape# for everything to work correctly in both clauses. When the condition changes I need to move the Escape so it is always in the False clause only.


@agocke commented on Tue Nov 03 2015

@paul1956 In the True case no escape could possibly help because the example given is nested inside a verbatim string literal (where the entire point is not having to escape things).


@paul1956 commented on Tue Nov 03 2015

@agocke I am not trying to engineer a solution just saying the is a real issue that should not be so easily dismissed.


@AraHaan commented on Fri Dec 29 2017

I got this issue on the C# Compiler in VS2017 when debug is not set too.

Also it can also be an python style comment on the string (where the string embeds python code like pytocs does to test on debug only)

https://github.com/uxmal/pytocs

  • Forum
  • Beginners
  • Issues with iostream and std namespace?

Issues with iostream and std namespace?

Hey, guys! Just recently started C++ and am having an issue with compiling a simple script.

Here is the source:

#include <iostream.h>

using namespace std;

int main() {
cout << «Hello, world!»;
cout << «I’m a C++ program»;
return 0;
}

I’m using Mono to compile it (via gmcs) and it gives me the following errors:

hello-world.cpp(2,0): error CS1024: Wrong preprocessor directive
hello-world.cpp(3,7): error CS1041: Identifier expected: `namespace’ is a keyword
hello-world.cpp(3,20): error CS1003: Syntax error, `.’ expected
hello-world.cpp(5,12): error CS8032: Internal compiler error during parsing, Run with -v for details

Any ideas on why this is giving me trouble?

Last edited on

Some (all) of the errors are funky, and that last one hints that you maybe should run the compiler with -v as an argument, if you know how.

This looks like a reinstall-fixable problem, though.

-Albatross

Last edited on

well it should be <iostream>, not <iostream.h>

But your errors don’t really make sense.

I didn’t know Mono was a compiler? I thought it was a .net runtime environment? Are you sure you’re actually using a C++ compiler?

Mono is for .Net, if you are using C++ ( ie not C# or C++/CLI ) you should use a C++ compiler

Actually, Disch++. Try compiling it with g++ and see if you get similar or the same errors. I also didn’t know Mono is an actual compiler.

-Albatross

Wow, guys. That is embarrassing… thank you for all of your help. I’ve got gcc and have attempted to use it — it still seems like it’s having an issue finding iostream. This is the output from gcc:

hello-world.c:1:20: error: iostream: No such file or directory
hello-world.c:3: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘namespace’
hello-world.c: In function ‘main’:
hello-world.c:6: error: ‘cout’ undeclared (first use in this function)
hello-world.c:6: error: (Each undeclared identifier is reported only once
hello-world.c:6: error: for each function it appears in.)

Use g++ instead of gcc or call gcc -std=c++98 -lstdc++
And remember about <iostream.h>

Last edited on

1
2
3
4
5
6
7
8
9
10
//#include <iostream.h> // NOT this!
#include <iostream> // Use this

using namespace std;

int main() {
cout << "Hello, world!";
cout << "I'm a C++ program";
return 0;	
}

Compile with:

g++ -o prog prog.cpp

Thanks a ton, everyone. That last suggestion you made fixed all of my problems, Bazzy.

Nice, Galik. Thank you! I can actually move on in the learning process now, thanks to all of you.

Topic archived. No new replies allowed.

Kristina-93

0 / 0 / 0

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

Сообщений: 28

1

Укажите на ошибку

11.12.2013, 23:24. Показов 2884. Ответов 15

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


Подскажите ошибку пожалуйста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <math.h>
using namespace std;
void main()
{locale::global(locale("rus"));//кириллица
int x,y,z;
cout<<"Введите x";
cin>>x;
if(x==1) cout<<"Январь";
else if(x==2) cout<<"Февраль";
else if(x==3) cout<<"Март";
else if(x==4) cout<<"Аперель";
else if(x==5) cout<<"Май";
else if(x==6) cout<<"Июнь";
else if(x==7) cout<<"Июль";
else if(x==8) cout<<"Август";
else if(x==9) cout<<"Сентябрь";
else if(x==10) cout<<"Октябрь";
else if(x==11) cout<<"Ноябрь";
else if(x==12) cout<<"Декабрь";
else cout<<"Не верно";
}

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



0



Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

11.12.2013, 23:24

Ответы с готовыми решениями:

Укажите на ошибку
Привет, есть проект, в нем был только один файл core.cpp
в нем было и объявления функций и их…

Укажите ошибку!
В строке удвоить все символы ‘&amp;’. Под вставкой символа n в строку после к-го элемента понимается…

Укажите на ошибку
Проблема с enum. Пишет что, нужно что-то перед enum. Поясните пожалуйста
#include &lt;iostream&gt;

Укажите ошибку пожалуйста
№ 3 вариант 8
#include &lt;iostream&gt;
#include &lt;math.h&gt;

using namespace std;

int main()
{ …

15

xtorne21st

интересующийся

311 / 282 / 93

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

Сообщений: 1,056

11.12.2013, 23:32

2

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
#include <iostream>
 
using namespace std;
 
int main()
{
    int x;
    locale::global(locale("rus"));//кириллица
 
    cout << "Введите x" << endl;
 
    cin >> x;
 
    if (x == 1) cout << "Январьn";
    else if (x == 2) cout << "Февральn";
    else if (x == 3) cout << "Мартn";
    else if (x == 4) cout << "Аперельn";
    else if (x == 5) cout << "Майn";
    else if (x == 6) cout << "Июньn";
    else if (x == 7) cout << "Июльn";
    else if (x == 8) cout << "Августn";
    else if (x == 9) cout << "Сентябрьn";
    else if (x == 10) cout << "Октябрьn";
    else if (x == 11) cout << "Ноябрьn";
    else if (x == 12) cout << "Декабрьn";
    else cout << "Не верноn";
}



0



0 / 0 / 0

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

Сообщений: 28

11.12.2013, 23:40

 [ТС]

3

xtorne21st, программа ругается



0



monolit

188 / 187 / 46

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

Сообщений: 670

11.12.2013, 23:49

4

Потому что

C++
1
return 0;

нету… Это как минимум, навскидку все нормально остальное.

Добавлено через 30 секунд
А вообще нужно указывать, на что она там ругается, мало ли, не телепаты тут сидят..



0



0 / 0 / 0

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

Сообщений: 28

11.12.2013, 23:55

 [ТС]

5

monolit, сообщения компилятора
prog.cs(2,0): error CS1024: Wrong preprocessor directive
prog.cs(3,6): error CS1041: Identifier expected, `namespace’ is a keyword
prog.cs(3,19): error CS1001: Unexpected symbol `;’, expecting identifier
prog.cs(7,4): error CS1041: Identifier expected, `int’ is a keyword
prog.cs(29,1): error CS8025: Parsing error
Compilation failed: 5 error(s), 0 warnings



0



1499 / 1145 / 165

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

Сообщений: 2,279

12.12.2013, 00:04

6

cs файлы — это C# а не c++.
ничего не перепутали?



1



0 / 0 / 0

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

Сообщений: 28

12.12.2013, 00:14

 [ТС]

7

ой! я тупица, сказывается ночное время и усталость

terminate called after throwing an instance of ‘std::runtime_error’
what(): locale::facet::_S_create_c_locale name not valid



0



xtorne21st

интересующийся

311 / 282 / 93

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

Сообщений: 1,056

12.12.2013, 00:22

8

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
#include <iostream>
#include <windows.h>
 
using namespace std;
 
int main()
{
    int x;
    setlocale(LC_ALL, "ru");
 
    cout << "Введите x" << endl;
 
    cin >> x;
 
    if (x == 1) cout << "Январьn";
    else if (x == 2) cout << "Февральn";
    else if (x == 3) cout << "Мартn";
    else if (x == 4) cout << "Аперельn";
    else if (x == 5) cout << "Майn";
    else if (x == 6) cout << "Июньn";
    else if (x == 7) cout << "Июльn";
    else if (x == 8) cout << "Августn";
    else if (x == 9) cout << "Сентябрьn";
    else if (x == 10) cout << "Октябрьn";
    else if (x == 11) cout << "Ноябрьn";
    else if (x == 12) cout << "Декабрьn";
    else cout << "Не верноn";
}



1



0 / 0 / 0

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

Сообщений: 28

12.12.2013, 00:34

 [ТС]

9

xtorne21st, только вот с кириллицей проблема)



0



интересующийся

311 / 282 / 93

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

Сообщений: 1,056

12.12.2013, 00:35

10

Что сейчас тоже не работает?



0



0 / 0 / 0

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

Сообщений: 28

12.12.2013, 04:55

 [ТС]

11

Работает, но в ответе непонятные символы) xtorne21st, вы слишком добры ко мне)))



0



188 / 187 / 46

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

Сообщений: 670

12.12.2013, 12:10

12

А в чем пишете то? В студии setlocale точно работает, в остальных не знаю.



0



интересующийся

311 / 282 / 93

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

Сообщений: 1,056

13.12.2013, 01:01

13

Попробуйте заменить все cout на wcout



0



5493 / 4888 / 831

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

Сообщений: 13,587

13.12.2013, 01:04

14

Цитата
Сообщение от xtorne21st
Посмотреть сообщение

Попробуйте заменить все cout на wcout

Не то.

Добавлено через 1 минуту

Цитата
Сообщение от monolit
Посмотреть сообщение

В студии setlocale точно работает,

Не только в студии.



0



xtorne21st

13.12.2013, 02:01

Не по теме:

Цитата
Сообщение от alsav22
Посмотреть сообщение

Не то.

А вдруг то?)



0



alsav22

13.12.2013, 02:11


    Укажите на ошибку

Не по теме:

Цитата
Сообщение от xtorne21st
Посмотреть сообщение

А вдруг то?)

Сомневаюсь я, однако…



0



Понравилась статья? Поделить с друзьями:
  • Main cpp 13 1 error expected unqualified id before token
  • Make error 2 ubuntu
  • Main controller data error mavic air как починить
  • Make error 193
  • Main control system error