Error invalid preprocessing directive

Добрый день, не так давно решил попробовать себя в проектах с ардуино, заказал с Али робота, все пришло, но с кетч оказался с ошибкой от китайцев я не знаю что делать так как ошибка точно не в библиотеке. Прошу помощи ребят которые разбираются в программирование так как я совсем в этом...
  • #1

Добрый день, не так давно решил попробовать себя в проектах с ардуино, заказал с Али робота, все пришло, но с кетч оказался с ошибкой от китайцев я не знаю что делать так как ошибка точно не в библиотеке. Прошу помощи ребят которые разбираются в программирование так как я совсем в этом новенький…
что делать с такой ошибкой ? как быть ?
Arduino: 1.8.13 (Windows 7), Плата:»Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)»
______________:4:3: error: invalid preprocessing directive #�

# определить DIRA1 34
^
_____________:7:3: error: invalid preprocessing directive #�
# определить DIRB1 37
^
______________:9:3: error: invalid preprocessing directive #�
# определите PWMC 9 / / C电机转速
^
______________:10:3: error: invalid preprocessing directive #�
# определить DIRC1 43

^
______________:12:3: error: invalid preprocessing directive #�

# определите PWMD 5 // D电机转速

^
______________:13:3: error: invalid preprocessing directive #�

# определить DIRD1 A4 / / 26

^
______________:14:3: error: invalid preprocessing directive #�

# определить DIRD2 A5 // 27 //D电机方向
^
______________:20:3: error: invalid preprocessing directive #�

# определить PS2_CLK 50 / / 17
^
______________:24:3: error: invalid preprocessing directive #�

# определить давление false

^
exit status 1
invalid preprocessing directive #�
Этот отчёт будет иметь больше информации с
включенной опцией Файл -> Настройки ->
«Показать подробный вывод во время компиляции»

1592472170994.png

Asked
9 years, 6 months ago

Viewed
39k times

I tried testing MinGW under Windows 7 with a simple Hello World program and got the following errors:

C:codehelloworld.cpp:2:2: error: invalid preprocessing directive #INCLUDE
C:codehelloworld.cpp:3:7: error: expected neested-name-specifier before 'namespace'
C:codehelloworld.cpp:3:17: error: expected ';' before 'std'
C:codehelloworld.cpp:3:17: error: 'std' does not name a type
C:codehelloworld.cpp: In function 'int main()':
C:codehelloworld.cpp:7:2: error: 'cout' was not declared in this scope

My original code was as follows:

//Hello, World
#INCLUDE <iostream>
using namesapce std;

int main()
{
    cout << "Hello, world!";
    return 0;
}

neatnick's user avatar

neatnick

1,4931 gold badge20 silver badges29 bronze badges

asked Aug 12, 2013 at 20:10

3

#include should be lower case. C++ is case sensitive.

P.P's user avatar

P.P

116k20 gold badges171 silver badges231 bronze badges

answered Aug 12, 2013 at 20:10

David Elliman's user avatar

It should be lowercase. Use #include.

Also, it’s using namespace std; (typo in namespace).

answered Aug 12, 2013 at 20:10

Jacob's user avatar

JacobJacob

34.1k14 gold badges109 silver badges165 bronze badges

#include <iostream>
using namespace std;

int main()
{
   cout << "Hello, world!";
   return 0;
}

answered Aug 12, 2013 at 20:11

LukeCodeBaker's user avatar

alien


  • #1

When i’m trying to compile a program with #DEFINE it says:
2:2: error: invalid preprocessing directive #DEFINE

Why, and how do i fix it?

Advertisements

Eric Sosman


  • #2

alien said:

When i’m trying to compile a program with #DEFINE it says:
2:2: error: invalid preprocessing directive #DEFINE

Why, and how do i fix it?

Try #define.

(Language lawyers: Was his compiler justified in
rejecting his code, assuming that it did? See 6.10,
fourth production of group-part; the Standard says very
little about this topic.)

kr0wie


  • #3

#define

Somehow you must have got a c source file from an oddball system that
doesn’t have lower case.

Okay. It works with #define, thanks for the quick answer.

Seebs


  • #4

When i’m trying to compile a program with #DEFINE it says:
2:2: error: invalid preprocessing directive #DEFINE

Why, and how do i fix it?

STOP SHOUTING AT YOUR COMPILER.

-s
p.s.: No, really. This is the correct answer to your question.

Tim Rentsch


  • #5

Eric Sosman said:

Try #define.

(Language lawyers: Was his compiler justified in
rejecting his code, assuming that it did? See 6.10,
fourth production of group-part; the Standard says very
little about this topic.)

My reading is that

#DEFINE <pp-tokens> <new-line>

(which presumably is what was there) is legal, and should not
have been rejected.

jameskuyper


  • #6

Kenneth said:

Based on what? Section 6.10 clearly shows several varations on «#define»,
but all are listed with lowercase «define», and I see nothing which states
or implies case insignificance.

Based upon 6.10p1, the production covering «# non-directive». Since
DEFINE satisfies the requirements for a pp-token, «DEFINE pp-tokens
new-line» matches the requirements for a «non-directive». The only
requirement imposed upon a non-directive is that it «shall not begin
with any of the directive names appearing in the syntax.» (6.10p3).
DEFINE is definitely not one of those directive names.

It might seem that the standard defines no behaviour for non-
directives; if that were the case, then the behaviour would be
undefined by reason of the absence of a definition.

However, there’s a tricky argument that can be made that the behavior
IS defined, though in a very minimalist way. The only other thing the
standard says about non-directives is to point out, in footnote 150,
that «Despite the name, a non-directive is a preprocessing
directive.». While non-normative, that note merely confirms what can
already be inferred from the normative grammar productions in 6.10p1.
Because a non-directive is a preprocessing directive, 5.1.1.2p4
applies, which says that at the end of translation phase 4 «All
preprocessing directives are then deleted.» Arguably, this defines the
behaviour of non-directives: they exist, like comments, solely for the
purpose of being removed without having any actual effect on the
translation of the program.

I’m not happy with this argument; I’d prefer a direct statement that
non-directives are simply to be ignored.

Advertisements

Tim Rentsch


  • #7

Kenneth Brody said:

Based on what? Section 6.10 clearly shows several varations on
«#define», but all are listed with lowercase «define», and I see
nothing which states or implies case insignificance.

6.4.2.1p2, «Lowercase and uppercase letters are distinct.»

Tim Rentsch


  • #8

Kenneth Brody said:

Based on what? Section 6.10 clearly shows several varations on
«#define», but all are listed with lowercase «define», and I see
nothing which states or implies case insignificance.

Sorry, I answered the wrong sense of your question earlier.

Given that case is significant, my statement was based on (a) syntax
rules in 6.10p1, specifically for ‘group-part:’ and ‘non-directive:’,
(b) the second sentence in 6.10p3 (‘DEFINE’ is different from
‘define’), and (c) the reassurance given in the footnote in 6.10.3p11.

The counter-argument is that, since there is no explicit definition
of behavior for a ‘non-directive’, the behavior is undefined. I don’t
have any substantial defense to offer in response to this argument
(my previous checking wasn’t thorough enough). Given that, I withdraw
my previous statement, and now venture to say that, since there is
no explicit definition of behavior, the compiler is within its
rights to do whatever it chooses, including rejecting the program.

Keith Thompson


  • #9

jameskuyper said:

Kenneth said:

Tim Rentsch wrote: […]

My reading is that

#DEFINE <pp-tokens> <new-line>

(which presumably is what was there) is legal, and should not
have been rejected.

Based on what? Section 6.10 clearly shows several varations on «#define»,
but all are listed with lowercase «define», and I see nothing which states
or implies case insignificance.

Based upon 6.10p1, the production covering «# non-directive». Since
DEFINE satisfies the requirements for a pp-token, «DEFINE pp-tokens
new-line» matches the requirements for a «non-directive». The only
requirement imposed upon a non-directive is that it «shall not begin
with any of the directive names appearing in the syntax.» (6.10p3).
DEFINE is definitely not one of those directive names.

It might seem that the standard defines no behaviour for non-
directives; if that were the case, then the behaviour would be
undefined by reason of the absence of a definition.

However, there’s a tricky argument that can be made that the behavior
IS defined, though in a very minimalist way. The only other thing the
standard says about non-directives is to point out, in footnote 150,
that «Despite the name, a non-directive is a preprocessing
directive.». While non-normative, that note merely confirms what can
already be inferred from the normative grammar productions in 6.10p1.
Because a non-directive is a preprocessing directive, 5.1.1.2p4
applies, which says that at the end of translation phase 4 «All
preprocessing directives are then deleted.» Arguably, this defines the
behaviour of non-directives: they exist, like comments, solely for the
purpose of being removed without having any actual effect on the
translation of the program.

I’m not happy with this argument; I’d prefer a direct statement that
non-directives are simply to be ignored.

I’d be even happier with a direct statement that non-directives
require a diagnostic, like any syntax error.

If I can write

#defnie SOME_IMPORTANT_SYMBOL

or

and have the compiler silently ignore it, that’s not a good thing.
Similarly, if I write:

#if SOME_CONDITION
this_code;
#elsif SOME_OTHER_CONDITION
that_code;
#endif

and both this_code and that_code are executed (because I typed
«#elsif» rather than «#elif»), that could lead to some bugs that
are very difficult to track down.

There’s very little discussion of them in the Standard. The Rationale
has this to say (6.10):

Neither text-line nor non-directive is implementation
defined. They are strictly defined as sequences of pp-tokens
followed by new-line. Each of these rules represents a placeholder
for an intermediate state in the phases of translation, and is
expressed as a non-terminal since it has no associated semantics
at this phase.

which is less than illuminating. If it were the intent that
non-directives are ignored, I presume the standard would say so,
as it does for the null directive.

I’ll post to comp.std.c in the vague hope of catching the attention
of someone who can explain the actual intent.

Willem


  • #10

Keith Thompson wrote:
) I’d be even happier with a direct statement that non-directives
) require a diagnostic, like any syntax error.

How about making it implementation-defined behaviour ?
Then you can read the docs of the compiler and be sure that it doesn’t
silently ignore those typoes.

SaSW, Willem

Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I’m not paranoid. You all think I’m paranoid, don’t you !
#EOT

Keith Thompson


  • #11

Willem said:

Keith Thompson wrote:
) I’d be even happier with a direct statement that non-directives
) require a diagnostic, like any syntax error.

How about making it implementation-defined behaviour ?
Then you can read the docs of the compiler and be sure that it doesn’t
silently ignore those typoes.

Just from a usability point of view, how would making it
implementation-defined be better than a mandatory diagnostic?

If I misspell a keyword, I get a diagnostic. If I misspell a
preprocessor directive name, I want the same thing. (And that’s
what I get on the two compilers I tried.)

Advertisements

jameskuyper


  • #12

Kenneth said:

jameskuyper said:

Kenneth said:

Tim Rentsch wrote: […]
My reading is that

#DEFINE <pp-tokens> <new-line>

(which presumably is what was there) is legal, and should not
have been rejected.
Based on what? Section 6.10 clearly shows several varations on «#define»,
but all are listed with lowercase «define», and I see nothing which states
or implies case insignificance.

Based upon 6.10p1, the production covering «# non-directive». Since
DEFINE satisfies the requirements for a pp-token, «DEFINE pp-tokens
new-line» matches the requirements for a «non-directive». The only
requirement imposed upon a non-directive is that it «shall not begin
with any of the directive names appearing in the syntax.» (6.10p3).
DEFINE is definitely not one of those directive names.

[… snip detailed analysis …]

I’m not happy with this argument; I’d prefer a direct statement that
non-directives are simply to be ignored.

While I agree with what you said for the most part, I would have to say that
allowing «anything» as a «non-directive» (which I agree the Standard says is
the case) to «simply be ignored» would be «A Bad Thing[tm]». Consider what
happens with a simple typo:

#defien SOME_CONFIG_FLAG 1

or

#if USE_VERSION == 1
… first version of the code …
#elseif USE_VERSION == 2
… second version …
#else
… default version …
#endif

or

#IfDef CONFIG_FLAG
… code …
#Endif

Try debugging that, and trying to figure out why the wrong conditional code
is being used.

While useful as a way of adding implementation-specific features, a
catch-all «comment» doesn’t sound good to me.

I agree; I was trying to figure out what the standard actually says,
and to suggest alternative wording that would make it clearer.
However, all the committee had to do to make a diagnostic mandatory
would have been to leave out non-directives entirely; they would then
have constituted syntax errors. In defining a «non-directive», the
committee went out of their way to make it not be a syntax error; I
presume they had a reason — I’m curious what it was. Until I know that
reason, and can judge it’s validity, I didn’t want to suggest changing
it to a syntax error.

Willem


  • #13

Keith Thompson wrote:
) Just from a usability point of view, how would making it
) implementation-defined be better than a mandatory diagnostic?

Extensibility, basically. Otherwise any compiler that recognizes
directives that are not defined in the standard would be required to emit a
diagnostic even though to them it’s something they’re perfectly happy with.

SaSW, Willem

Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I’m not paranoid. You all think I’m paranoid, don’t you !
#EOT

Keith Thompson


  • #14

Willem said:

Keith Thompson wrote:
) Just from a usability point of view, how would making it
) implementation-defined be better than a mandatory diagnostic?

Extensibility, basically. Otherwise any compiler that recognizes
directives that are not defined in the standard would be required to emit a
diagnostic even though to them it’s something they’re perfectly happy with.

We have exactly the same situation with extensions.

If a compiler defines an extension, say, a «long long long» type, it’s
still required to issue a diagnostic for any occurrence of «long long
long»; it’s then free to continue compilation and implement whatever
behavior it likes. If you want to use «long long long» without being
bothered by diagnostics, just invoke the compiler in a non-conforming
mode. You can use the extension, and I can still get a diagnostic if
I type «long» more times than I intended to.

In any case, I don’t think that was the intent. As the Rationale says:

Neither text-line nor non-directive is implementation
defined. They are strictly defined as sequences of pp-tokens
followed by new-line. Each of these rules represents a placeholder
for an intermediate state in the phases of translation, and is
expressed as a non-terminal since it has no associated semantics
at this phase.

However, these sequences of pp-tokens are still subject to normal
processing in the subsequent phases of translation.

My best guess is that the intent was that a non-directive would never
survive all the phases of translation. I just can’t figure out how
that’s supposed to happen. I’m hoping my query in comp.std.c will
produce either a definitive answer or an acknowledgement that the
standard’s text doesn’t properly describe the intent.

Tim Rentsch


  • #15

jameskuyper said:

Based upon 6.10p1, the production covering «# non-directive». Since
DEFINE satisfies the requirements for a pp-token, «DEFINE pp-tokens
new-line» matches the requirements for a «non-directive». The only
requirement imposed upon a non-directive is that it «shall not begin
with any of the directive names appearing in the syntax.» (6.10p3).
DEFINE is definitely not one of those directive names.

It might seem that the standard defines no behaviour for non-
directives; if that were the case, then the behaviour would be
undefined by reason of the absence of a definition.

However, there’s a tricky argument that can be made that the behavior
IS defined, though in a very minimalist way. The only other thing the
standard says about non-directives is to point out, in footnote 150,
that «Despite the name, a non-directive is a preprocessing
directive.». While non-normative, that note merely confirms what can
already be inferred from the normative grammar productions in 6.10p1.
Because a non-directive is a preprocessing directive, 5.1.1.2p4
applies, which says that at the end of translation phase 4 «All
preprocessing directives are then deleted.» Arguably, this defines the
behaviour of non-directives: they exist, like comments, solely for the
purpose of being removed without having any actual effect on the
translation of the program.

I’m not happy with this argument; I’d prefer a direct statement that
non-directives are simply to be ignored.

The problem is, 5.1.1.2p4 says «Preprocessing directives are
executed,» but there is no statement of what behavior occurs
when a ‘non-directive’ is executed. There is for every other
preprocessing directive (including ‘# <new-line>’). It’s
this absence that convinved me that an unskipped ‘non-directive’
is undefined behavior.

Tim Rentsch


  • #16

Keith Thompson said:

We have exactly the same situation with extensions.

If a compiler defines an extension, say, a «long long long» type, it’s
still required to issue a diagnostic for any occurrence of «long long
long»; it’s then free to continue compilation and implement whatever
behavior it likes. If you want to use «long long long» without being
bothered by diagnostics, just invoke the compiler in a non-conforming
mode. You can use the extension, and I can still get a diagnostic if
I type «long» more times than I intended to.

In any case, I don’t think that was the intent. As the Rationale says:

Neither text-line nor non-directive is implementation
defined. They are strictly defined as sequences of pp-tokens
followed by new-line. Each of these rules represents a placeholder
for an intermediate state in the phases of translation, and is
expressed as a non-terminal since it has no associated semantics
at this phase.

However, these sequences of pp-tokens are still subject to normal
processing in the subsequent phases of translation.

My best guess is that the intent was that a non-directive would never
survive all the phases of translation.

Right. It’s deleted at the end of phase 4 (assuming that the UB
that arises from «executing» it doesn’t contradict that).

I just can’t figure out how that’s supposed to happen.

It gets deleted because of the last sentence of 5.1.1.2p1.4 says
it will be (oops, bad reference in a previous posting). The
question is what happens when it gets executed, and the Standard
doesn’t say anything about that, which is what makes the behavior
undefined.

I’m hoping my query in comp.std.c will
produce either a definitive answer or an acknowledgement that the
standard’s text doesn’t properly describe the intent.

It’s there to make sure that every line starting with ‘#’ is
considered a preprocessing directive, and it’s undefined to
give implementations a chance to define them. It just would be
nice if that had been handled a little better and been made
a little more clear in the Standard.

Advertisements

James Kuyper


  • #17

Kenneth said:

jameskuyper said:

Kenneth Brody wrote: […]

While useful as a way of adding implementation-specific features, a
catch-all «comment» doesn’t sound good to me.

I agree; I was trying to figure out what the standard actually says,
and to suggest alternative wording that would make it clearer.
However, all the committee had to do to make a diagnostic mandatory
would have been to leave out non-directives entirely; they would then
have constituted syntax errors. In defining a «non-directive», the
committee went out of their way to make it not be a syntax error; I
presume they had a reason — I’m curious what it was. Until I know that
reason, and can judge it’s validity, I didn’t want to suggest changing
it to a syntax error.

It doesn’t have to be a «syntax error» to be an «error». After all, the
following isn’t a «syntax error», either:

I would want a diagnostic to be mandatory; the simplest way to make that
happen is to make it a syntax error, by removing ‘non-directive’ from
the grammar. Of course, a constraint violation or an explicit statement
that a diagnostic is required would do just as well.

This would not prevent the development of implementation-specific
preprocessing directives. In conforming mode, a compiler could issue a
diagnostic saying «warning: non-standard feature #explain used», and
that warning could be turned off by an option that would render the
compiler non-conforming.

My point is — the committee went out of their way to put «non-directive»
into the grammar. Why? Until I know why, I don’t want to suggest
removing it. Keith’s inquiry on comp.std.c has received no authoritative
response yet, which is a bit disappointing.

jacob navia


  • #18

James Kuyper a écrit :

My point is — the committee went out of their way to put «non-directive»
into the grammar. Why? Until I know why, I don’t want to suggest
removing it. Keith’s inquiry on comp.std.c has received no authoritative
response yet, which is a bit disappointing.

Well, this is just a bug.

Nobody is perfect, and committee members aren’t either.

The preprocessor of lcc-win uses is a version that was written by Dennis Ritchie.
I have maintained his code for many years, and he does complain at any
directive that is not a known directive. This bug in the specs was introduced
later, and I am glad his version doesn’t have it.

Keith Thompson


  • #19

jacob navia said:

James Kuyper a écrit :

Well, this is just a bug.

Nobody is perfect, and committee members aren’t either.

The preprocessor of lcc-win uses is a version that was written by
Dennis Ritchie. I have maintained his code for many years, and he
does complain at any directive that is not a known directive. This
bug in the specs was introduced later, and I am glad his version
doesn’t have it.

Assuming that the behavior of a «non-directive» is undefined,
Ritchie’s preprocessor is consistent with the spec, at least with
respect to this feature.

Advertisements

Keith Thompson


  • #20

Tim Rentsch said:

Right. It’s deleted at the end of phase 4 (assuming that the UB
that arises from «executing» it doesn’t contradict that).

It gets deleted because of the last sentence of 5.1.1.2p1.4 says
it will be (oops, bad reference in a previous posting). The
question is what happens when it gets executed, and the Standard
doesn’t say anything about that, which is what makes the behavior
undefined.

Ok. The reference paragraph, which describes translation phase 4,
says

Preprocessing directives are executed, macro invocations are
expanded, and _Pragma unary operator expressions are executed.
[snip]
All preprocessing directives are then deleted.

And yes, the meaning of executing a non-directive (which is a
directive) is the sticking point. Since the standard doesn’t define
the behavior, the behavior is undefined.

It’s there to make sure that every line starting with ‘#’ is
considered a preprocessing directive, and it’s undefined to
give implementations a chance to define them. It just would be
nice if that had been handled a little better and been made
a little more clear in the Standard.

I have a much clearer understanding of what the standard *says*
about non-directives. But I’m still waiting for a definitive
statement about the intent. (Such a statement cannot be based
only on the wording of the standard; it’s about the state of mind
of the authors.)

The standard would be substantially improved by an explicit
statement that the behavior of executing a non-directive is
undefined. It would be improved even more, IMHO, by a statement
that executing a non-directive is a constraint violation. If I
misspell a keyword, the compiler complains, and in most cases
it’s required to complain. The (apparent) fact that this doesn’t
apply to misspelled preprocessor directives is counterintuitive.
This would still leave room for implementation-defined extensions.

(I thought about using the common extension «#warning» as an example,
but since the whole purpose of «#warning» is to trigger a diagnostic,
it’s probably the worst possible example.)

  • Posts

Hot!How to fix the error «invalid preprocessing directive»?

Post


Essentials Only

Full Version

Nicetomeetyou

Starting Member

  • Total Posts : 47
  • Reward points : 0
  • Joined: 2021/06/21 01:31:41
  • Location: 0
  • Status: offline



2022/04/20 02:01:54

(permalink)

0

Dear All,

 I tried to compile a demo code that related to memory access.
And i got error message like this:
../nvm.c:444:2: error: invalid preprocessing directive
#assert NVM_KLQ_SYNC_SIZE == 2
^

(I also attached the error photo)

 It seem that compiler doesnt support command #assert.
May I know any one in this forum has seem similar failure before?
And any method to fix the problem?

 Thank you,
Best Regards,

  Peter

Attached Image(s)

#1

ric

Super Member

  • Total Posts : 35931
  • Reward points : 0
  • Joined: 2003/11/07 12:41:26
  • Location: Australia, Melbourne
  • Status: offline

Re: How to fix the error «invalid preprocessing directive»?


2022/04/20 02:06:14

(permalink)

-1 (1)

Whenever you get a string of errors, fix the FIRST one reported first.
More often than not, subsequent errors are a side effect of the earlier ones.

I also post at: PicForum
To get a useful answer, always state which PIC you are using!

#2

Gort2015

Klaatu Barada Nikto

  • Total Posts : 6043
  • Reward points : 0
  • Joined: 2015/04/30 10:49:57
  • Location: 0
  • Status: offline

Re: How to fix the error «invalid preprocessing directive»?


2022/04/20 02:39:33

(permalink)

-1 (1)

When you type, ‘#’ does mplabx display a drop down list ?

 #assert and #unassert are gcc extentions and use parenthesis.

 #include <assert.h>
int x = 42;

 x *= 2;

 #assert (x == 84)
#assert (x == 42)  output assertion failed (x == 42)

MPLab X playing up, bug in your code? Nevermind, Star Trek:Discovery will be with us soon.
https://www.youtube.com/watch?v=Iu1qa8N2ID0
+ ST:Continues, «What Ships are Made for», Q’s back.

#3

© 2023 APG vNext Commercial Version 4.5

Басаман Максим

1 / 1 / 0

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

Сообщений: 43

1

12.11.2013, 01:50. Показов 4748. Ответов 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <stdio.h>
#define SIZE 18
 
void search(int [], int);
void MaxMin(int [], int);
void increase(int [], int);
 
main()
{
    int arr[SIZE] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17};
 
    void search(arr, SIZE);
    void MaxMin(arr, SIZE);
    void increase(arr, SIZE);
 
}
 
void search(int a[], int size) //произведение на позициях кратных трем
{
    int f1 = 1;
 
    for (int i = 0; i < size; i++)
    {
        if (i % 3 == 0)
            f1 *= a[i]
    }
}
 
void MaxMin(int a[], int size) //нахождение квадратов
{
    int max = a[0], min = a[0];
    int A[size]; //в этом массиве будут храниться все квадраты нужных нам чисел
 
    for (int i = 0; i < size; i++)
    {
        if (max < a[i]) max = i;
        if (min > a[i]) min = i;
    }
 
    int begin = min < max ? min : max;
    int end = min > max ? min : max;
 
    for (int i = 0; begin <= end; begin++)
    {
        A[i] = a[begin] * a[begin];
        i++;
    }
}
 
void increase(int a[], int size)  //сортировка по возрастанию всех элементов не кратных трем
{
    int hold;
 
    for (int i = 0; i < size; i++)
        for (int j = 0; j < size; j++)
            if (i % 3 != 0 && a[i] > a[i + 1])
            {
                hold = a[i];
                a[i] = a[i + 1];
                a[i + 1] = hold;
            }   
}

————— Build: Debug in 11 (compiler: GNU GCC Compiler)—————

mingw32-gcc.exe -Wall -g -c C:UsersMaxDesktop11main.c -o objDebugmain.o
C:UsersMaxDesktop11main.c:2:3: error: invalid preprocessing directive #std
C:UsersMaxDesktop11main.c:9:1: warning: return type defaults to ‘int’ [-Wreturn-type]
C:UsersMaxDesktop11main.c: In function ‘main’:
C:UsersMaxDesktop11main.c:13:22: error: expected ‘)’ before numeric constant
C:UsersMaxDesktop11main.c:14:22: error: expected ‘)’ before numeric constant
C:UsersMaxDesktop11main.c:15:24: error: expected ‘)’ before numeric constant
C:UsersMaxDesktop11main.c:11:9: warning: unused variable ‘arr’ [-Wunused-variable]
C:UsersMaxDesktop11main.c: In function ‘search’:
C:UsersMaxDesktop11main.c:23:5: error: ‘for’ loop initial declarations are only allowed in C99 mode
C:UsersMaxDesktop11main.c:23:5: note: use option -std=c99 or -std=gnu99 to compile your code
C:UsersMaxDesktop11main.c:27:5: error: expected ‘;’ before ‘}’ token
C:UsersMaxDesktop11main.c: In function ‘MaxMin’:
C:UsersMaxDesktop11main.c:35:5: error: ‘for’ loop initial declarations are only allowed in C99 mode
C:UsersMaxDesktop11main.c:44:14: error: redefinition of ‘i’
C:UsersMaxDesktop11main.c:35:14: note: previous definition of ‘i’ was here
C:UsersMaxDesktop11main.c:44:5: error: ‘for’ loop initial declarations are only allowed in C99 mode
C:UsersMaxDesktop11main.c:33:9: warning: variable ‘A’ set but not used [-Wunused-but-set-variable]
C:UsersMaxDesktop11main.c: In function ‘increase’:
C:UsersMaxDesktop11main.c:55:5: error: ‘for’ loop initial declarations are only allowed in C99 mode
C:UsersMaxDesktop11main.c:56:9: error: ‘for’ loop initial declarations are only allowed in C99 mode
C:UsersMaxDesktop11main.c: In function ‘main’:
C:UsersMaxDesktop11main.c:17:1: warning: control reaches end of non-void function [-Wreturn-type]
Process terminated with status 1 (0 minutes, 0 seconds)
11 errors, 4 warnings (0 minutes, 0 seconds)

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



0



anmartex

1804 / 1268 / 935

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

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

12.11.2013, 08:07

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <stdio.h>
#define SIZE 18
 
void search(int [], int);
void MaxMin(int [], int);
void increase(int [], int);
 
int main()
{
    int arr[SIZE] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17};
 
    search(arr, SIZE);
    MaxMin(arr, SIZE);
    increase(arr, SIZE);
 
    return 0;
}
 
void search(int a[], int size) //произведение на позициях кратных трем
{
    int f1 = 1;
    int i;
    for (i = 0; i < size; i++)
    {
        if (i % 3 == 0)
        {
            f1 *= a[i];
        }
    }
}
 
void MaxMin(int a[], int size) //нахождение квадратов
{
    int max = a[0], min = a[0];
    int A[size]; //в этом массиве будут храниться все квадраты нужных нам чисел
    int i;
 
    for (i = 0; i < size; i++)
    {
        if (max < a[i])
        {
            max = i;
        }
        if (min > a[i])
        {
            min = i;
        }
    }
 
    int begin = min < max ? min : max;
    int end = min > max ? min : max;
 
    for (i = 0; begin <= end; begin++)
    {
        A[i] = a[begin] * a[begin];
        i++;
    }
}
 
void increase(int a[], int size)  //сортировка по возрастанию всех элементов не кратных трем
{
    int hold;
    int i, j;
 
    for (i = 0; i < size; i++)
        for (j = 0; j < size; j++)
            if (i % 3 != 0 && a[i] > a[i + 1])
            {
                hold = a[i];
                a[i] = a[i + 1];
                a[i + 1] = hold;
            }
}



0



419 / 418 / 167

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

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

12.11.2013, 10:25

3

Басаман Максим, у вас есть 3 варианта:
1) включать опцию -std=c99
2) создавать проект С++ и писать в нем на Си.
3) прочитать требования к написанию кода в Си (до Си 99), который требует объявления всех переменных в начале функции, т.е. объявлять переменную в цикле нельзя.



0



 
No such file or directory
This error occurs if GCC cannot find a requested file on its search
path. The file may have been specified on the command-line, or with a
preprocessor #include statement. Either the filename has been
spelled incorrectly or the directory for the file needs to be added to the
include path or link path.
Example:

#include <stdoi.h>  /* incorrect */

int
main (void)
{
  printf ("Hello World!n");
  return 0;
}

The program above tries to include the non-existent file ‘stdoi.h’
giving the error ‘stdoi.h: No such file or directory’. The correct
filename should be ‘stdio.h’.

macro or '#include' recursion too deep
#include nested too deeply
This error occurs if the preprocessor encounters too many nested
‘#include’ directives. It is usually caused by two or more files
trying to include each other, leading to an infinite recursion.
Example:

/* foo.h */
#include "bar.h"
...
/* bar.h */
#include "foo.h"
...

The solution to this problem is to ensure that files do not mutually
include each other, or to use «include guards» (see section 7.4.2 Providing your own templates for an example).

invalid preprocessing directive #...
This error indicates that the preprocessor encountered an unrecognized
# command.
Example:

#if FOO
   int x = 1;
#elsif BAR   /* should be #elif */
   int x = 2;
#else     
   int x = 3;
#endif

The preprocessor syntax requires #elif for the «else if» condition in
#if blocks, rather than #elseif. In the example above
an invalid directive error occurs at the incorrect usage
#elseif, but only when FOO is defined (otherwise the
preprocessor ignores everything up to the #else statement).

warning: This file includes at least one deprecated or antiquated header.
This warning is generated for C++ programs which include old-style
library header files, such as ‘iostream.h’, instead of the modern
C++ library headers without the ‘.h’ extension. The old headers
import their functions into the top-level global namespace, instead of
using the std:: namespace. Note that old-style header files are
still supported, so this message is only a warning and existing programs
will continue to compile. The message is actually generated by a
#warning directive in the old header files, and not by the
preprocessor itself.
Example:

#include <iostream.h>  /* old style */

int
main (void)
{
  cout << "Hello World!n";
  return 0;
}

This program uses an old-style header file ‘iostream.h’. It could
be updated to use #include <iostream> and std::cout
instead.

Ezoic

 

I was fighting with Haskell last weekend. At first, I couldn’t install some missing libraries with Cabal, and then, when trying to find out what’s wrong, I ended up removing the whole Haskell installation — only to find out I could no longer install neither the Haskell Platform nor even just Cabal Install! The warnings I would see were more or less about the use of the single quote in source code:

Preprocessing library text-0.11.2.3...

Data/Text.hs:6:52:
     warning: missing terminating ' character [-Winvalid-pp-token]
-- Copyright   : (c) 2009, 2010, 2011, 2012 Bryan O'Sullivan,
                                                   ^

The errors that finally prevented the installation, were about having non-preprocessor-directive lines start with # in Haskell files that should be preprocessed with the C preprocessor (CPP):

Data/Text.hs:442:3:
     error: invalid preprocessing directive
     #-}

(I should mention here, by the way, that Clang is all correct in rejecting these source files: it’s trying to protect poor coders from writing e.g. #elsif where #elif would be needed! It’s just that Haskellers are used to a less strict version of the C preprocessor, one that’s been supported by the GNU compiler since ages ago.)

I copied both the above warnings and the error from the Haskell text package bug report haskell/text#53, but similar problems have been previously cited in the GHC bug tracker as well as Homebrew bug tracker about cabal-install.

I asked about the problem in the #haskell IRC channel but I’m unsure where the source of this problem should be actually fixed:

  • a) in broken packages (i.e. by moving the closing pragma markers, #-}, to the end of the preceding line),
  • b) in the Homebrew formulas (in that case, I guess it would be best to fix the GHC formula), or
  • c) in GHC itself, to make it not use the current C compiler for preprocessing Haskell source files (there’s a Haskell implementation of the CPP in http://hackage.haskell.org/package/cpphs-1.16 but some commenters in IRC were concerned about the LGPL-mode licensing.)

So before we’ll find a satisfactory permanent solution, here’s my quick interim fix for the problem.

QUICKFIX: Steps to install Haskell Platform on Mac OS X

…with Homebrew and a very recent version of Clang.

  1. Install Glasgow Haskell Compiler 7.6.3. (This would be installed by brew install haskell-platform anyway, but we need it before that.)

    brew install ghc
    
  2. Enable installation of GCC versions, and install e.g. gcc-4.7.

    brew tap homebrew/versions
    brew install gcc47
    
  3. GHC uses /usr/bin/gcc by default, which is actually Clang. And apparently, new Clang versions don’t support the -traditional GCC option that makes the C preprocessor work in a friendly manner to Haskell files. So, instead of using Clang as the preprocessor, reconfigure the GHC compiler script to compile with /usr/local/bin/gcc-4.7 instead.

    nano /usr/local/Cellar/ghc/7.6.3/lib/ghc-7.6.3/settings
    

    (In the above file, replace the second line:

    ("C compiler command", "/usr/bin/gcc"),
    

    with:

    ("C compiler command", "/usr/local/bin/gcc-4.8"),
    
  4. Now you should be good to install Haskell Platform – or just cabal-install if that’s what you like.

    brew install haskell-platform
    

This should now work out with reasonably few problems, warnings or errors.

(At least, I’m keeping my fingers crossed!)

— @pyrtsa, 2013-08-12.

Я наткнулся на следующую ошибку компиляции в C ++ с компилятором g ++:

error on line line 1 with message:
invalid preprocessing directive #a

(с кареткой над символом а), за которой следует еще одна, вероятно, последующая ошибка в строке 4 с сообщением:

cout was not declared in this scope.

Я использую редактор с блоками кода 10.05 с mingw. Я попытался удалить расширение .h из оператора include файла iostream, переключиться между различными вариантами кодирования файлов, а также заменить угловую скобку одинарными и двойными кавычками. Я застрял на извините, если это дубликат (хотя я прошел через несколько уже заданных вопросов по релевантности).
Следующий код иллюстрирует проблему:

#‪include ‬<iostream.h>
int main()
{
cout<< "abc"+8;
cout<< "def"+4;
cout<< "ha";
return 0;
}

-1

Решение

cout существует в пространстве имен std

Так что либо

#‪include‬<iostream>
//...
std::cout << "abc" << 8;
//...

или же

#‪include‬<iostream>
using namespace std;

//...

или же

#‪include‬<iostream>
using std::cout;

//...

Я обычно предпочитаю первый, если я использую его только один или два раза, второй, если я использую много разных частей из пространства имен (и только в файле cpp), или третий, если я использую только кусок или 2 из пространства имен, но используя одну и ту же пару раз.

Кроме того, как указано в комментариях, не используйте второй в заголовках. Увидеть: «используя пространство имен» в заголовках с ++

Кроме того, в вашем #include есть недопустимый символ. Вы можете увидеть это в шестнадцатеричном редакторе или заметьте, что stackoverflow не выделяет их одинаково:

#‪include‬<iostream>
#include<iostream>

Полностью рабочий код:

#include<iostream>

using std::cout;

int main()
{
cout << "abc" << 8;
cout << "def" << 4;
cout << "ha";
return 0;
}

Производит следующий вывод abc8def4ha после того, как я исправил попытку добавить 8 к char*

2

Другие решения

Вы должны использовать std :: cout, что означает, что ключевое слово «cout» является частью стандартной библиотеки.

2

Ошибка «неверная директива» вызвана некоторыми невидимыми символами Юникода в #include директива; возможно, вы скопировали это с веб-сайта, на котором были вставлены символы форматирования в коде. Их можно увидеть в вопросе, если вы посмотрите на источник в шестнадцатеричном редакторе. Эта ошибка должна быть исправлена ​​путем удаления и повторного ввода #include линия.

Вероятно, у вас будут другие ошибки, так как код устарел на пятнадцать лет; большинство современных компиляторов не предоставляют предварительно стандартные библиотеки. В наши дни стандартные заголовки библиотеки не имеют .h расширение:

#include <iostream>

и почти все имена, которые они объявляют, находятся внутри std Пространство имен:

std::cout << "ha";

В заключение, "abc"+8 не делает ничего толкового. Строковый литерал представляет собой массив из четырех символов, и +8 пытается дать вам указатель на девятый символ, который не существует. Результатом является неопределенное поведение.

Если вы хотите напечатать «abc», а затем «8», то вы хотите:

std::cout << "abc" << 8;

2

Попробуйте использовать это так:

#‪include ‬<iostream>
using std :: cout;

cout является частью std библиотека

1

Если у вас есть курсор выше a, попробуйте еще раз набрать #include.
Вы можете случайно набрать альтернативу I, которая похожа, но имеет другой код.
Предложения о std :: имеют отношение только ко второй получаемой вами ошибке.
Я также не до конца понял, чего вы пытались достичь с помощью «abc» +8.

1

Понравилась статья? Поделить с друзьями:
  • Error invalid path specified
  • Error invalid parameters перевод
  • Error invalid parameter 87 0x57
  • Error invalid ota package missing scatter
  • Error invalid or corrupt jarfile что делать майнкрафт