Cs1024 требуется директива препроцессора как исправить

I'm just trying to use MS Visual for some really simple C++ coding for school purposes. The point is I can't even write a simple hello-world alike program. I've got that error "Preprocessor expecte...

I’m just trying to use MS Visual for some really simple C++ coding for school purposes. The point is I can’t even write a simple hello-world alike program.
I’ve got that error «Preprocessor expected» in line with library. Line with code looks like this: #include <iostream>

Any help with solving this (probably) minor problem is welcomed.

Here is whole code:

#include <iostream>

int main()
{
    std::cout << "aogaohgo";
}

Brian Tompsett - 汤莱恩's user avatar

asked Oct 8, 2015 at 16:11

flwn's user avatar

3

OP’s reported error message is reminiscent of a C# error message.

Testing this theory and pasting OPs C++ code into a C# console project I receive:

error CS1024: Preprocessor directive expected

As the first error.

Solution: Create a new project and make sure the selected language is C++

answered Oct 8, 2015 at 17:44

user4581301's user avatar

user4581301user4581301

32.5k7 gold badges32 silver badges53 bronze badges

#include isn’t valid on it’s own.

The correct syntax is #include <filename>.

I suggest you pick up a better Hello World tutorial :)

answered Oct 8, 2015 at 16:13

slaphappy's user avatar

slaphappyslaphappy

6,8663 gold badges33 silver badges59 bronze badges

2

Содержание

  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-секции встречается строка, первый непробельный символ в которой — #, то эта строка должна содержать корректную директиву препроцессора, иначе возникает ошибка компиляции. Я бы не сказал, что эта мысль ясно выражена в стандарте.

Источник

Максим Зайцев

1 / 1 / 0

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

Сообщений: 38

1

Сделать переход по кнопке от первой формы ко второй. Ожидается директива препроцессора

06.10.2014, 17:13. Показов 1373. Ответов 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
28
29
30
31
32
33
34
#include<test2> // - error CS1024: Ожидается директива препроцессору
                                  // - error CS1025: Ожидался однострочный комментарий или признак конца строки
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void label1_Click(object sender, EventArgs e)
        {
 
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            this.Hide();
            test2.Show();
        }
    }
}

осваиваю microsoft visual studio 2013 Windows Forms
нужно сделать переход по кнопке от первой формы ко второй.

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



0



Супер-модератор

Эксперт Pascal/DelphiАвтор FAQ

32451 / 20945 / 8105

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

Сообщений: 36,213

Записей в блоге: 7

06.10.2014, 17:23

2

Цитата
Сообщение от Максим Зайцев
Посмотреть сообщение

в чем ошибка?

В том, что это не С++, а C#…

Перенесено в правильный раздел.



0



meksik

202 / 171 / 67

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

Сообщений: 839

06.10.2014, 17:46

3

Не по теме:

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

В том, что это не С++, а C#…

под столом:rofl:

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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void label1_Click(object sender, EventArgs e)
        {
 
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            From2 form2  = new Form2(); //Form2 должна быть закрыта
            form2.Show();
            this.Hide(); //или this.Close() если это не главная форма приложения;
        }
    }
}

Код для второй формы. Получится так что нажав на кнопку в Form1 открываем Form2 и наоборот до бесконечности)

Кликните здесь для просмотра всего текста

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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            Form1 form1 = new Form1();
            form1.Show();
            this.Close();
        }
    }
}



1



Понравилась статья? Поделить с друзьями:
  • Cs0297c ошибка e98
  • Cs0297c ошибка e01
  • Cs0263c ошибка e99
  • Cs0263c ошибка e01
  • Cs0261f ошибка e99