-
#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 #�
Этот отчёт будет иметь больше информации с
включенной опцией Файл -> Настройки ->
«Показать подробный вывод во время компиляции»
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
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
116k20 gold badges171 silver badges231 bronze badges
answered Aug 12, 2013 at 20:10
It should be lowercase. Use #include
.
Also, it’s using namespace std;
(typo in namespace
).
answered Aug 12, 2013 at 20:10
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
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 #DEFINEWhy, 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 #DEFINEWhy, 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 …
#endifor
#IfDef CONFIG_FLAG
… code …
#EndifTry 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»? ![](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)
Post Essentials Only Full Version |
---|
Nicetomeetyou
Starting Member
0 Dear All, I tried to compile a demo code that related to memory access. (I also attached the error photo) It seem that compiler doesnt support command #assert. Thank you, Peter Attached Image(s)#1 |
ric
Super Member
Re: How to fix the error «invalid preprocessing directive»?
-1 (1) Whenever you get a string of errors, fix the FIRST one reported first. I also post at: PicForum #2 |
Gort2015
Klaatu Barada Nikto
Re: How to fix the error «invalid preprocessing directive»?
-1 (1) When you type, ‘#’ does mplabx display a drop down list ? #assert and #unassert are gcc extentions and use parenthesis. #include <assert.h> x *= 2; #assert (x == 84) MPLab X playing up, bug in your code? Nevermind, Star Trek:Discovery will be with us soon. #3 |
© 2023 APG vNext Commercial Version 4.5
Басаман Максим 1 / 1 / 0 Регистрация: 26.09.2013 Сообщений: 43 |
||||
1 |
||||
12.11.2013, 01:50. Показов 4748. Ответов 2 Метки нет (Все метки)
————— Build: Debug in 11 (compiler: GNU GCC Compiler)————— mingw32-gcc.exe -Wall -g -c C:UsersMaxDesktop11main.c -o objDebugmain.o
__________________
0 |
anmartex … 1804 / 1268 / 935 Регистрация: 12.02.2013 Сообщений: 2,063 |
||||
12.11.2013, 08:07 |
2 |
|||
Логику не смотрел, но компилироваться будет.
0 |
419 / 418 / 167 Регистрация: 28.11.2010 Сообщений: 1,183 |
|
12.11.2013, 10:25 |
3 |
Басаман Максим, у вас есть 3 варианта:
0 |
|
||
|
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.
-
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
-
Enable installation of GCC versions, and install e.g. gcc-4.7.
brew tap homebrew/versions brew install gcc47
-
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"),
-
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