I'm having a bit of trouble compiling and running my .c file in terminal. First, when compiling, I see:
HW3.c: In function ‘main’:
HW3.c:87:5: error: ‘for’ loop initial declarations are only allowed in C99 mode
for(int j = 0; j < 10; j++) {
^
HW3.c:87:5: note: use option -std=c99 or -std=gnu99 to compile your code
HW3.c:100:5: error: ‘for’ loop initial declarations are only allowed in C99 mode
for(int j = 0; j < 10; j++) {
^
All of my variables are declared and assigned at the beginning of the program, including j, so I'm not sure why I'm seeing an error about 'for' loop initial declarations.
Secondly, when attempting to run my program, I type:
./a.out HW3.c
and see error
./a.out: Command not found.
What could possibly be the issue here? Is it not running because of the error in compiling? I'm sure I have the command right, right..? Let me know if you need to see the whole program to help, it's not too long, I could copy it over. Thanks!
If j is already declared at the beginning of the program, then remove the int part of for (int j:
for(j = 0; j < 10; j++) {
You can declare j inside the for loop, as you seem to have attempted to do, but you would need to tell your compiler to support a newer revision of the C standard.
You need to add a more recent C standard revision to your compiler options. Try adding the flag --std=c99 and it should work.
As for your second problem, a.out is the executable produced by the compiler. If there are errors in the program, it won't produce an executable, so you have to fix the errors.
You can also specify the name of the executable with the -o flag:
gcc -std=c99 HW3.c -o HW3
This will produce an executable named HW3.
Related
I would like to have compiler throw an error every time there is a declaration after statement because that is the coding style I want to enforce, but I also want to compile with -std=c99 since I use some of the specific c99 features.
The problem is that in c99 declarations are allowed anywhere in the code, not just at the beginning of a block.
Take a look at the following program:
// prog.c
#include <stdio.h>
int main(void)
{
printf("hello world\n");
int i = 0;
return 0;
}
If I compile this code with gcc like this:
gcc -std=c99 -Werror=declaration-after-statement prog.c
it throws the following error:
prog.c: In function ‘main’:
prog.c:6:9: error: ISO C90 forbids mixed declarations and code [-Werror=declaration-after-statement]
6 | int i = 0;
| ^~~
cc1: some warnings being treated as errors
This is the behavior I would like to have when compiling with clang, but clang behaves differently.
If I compile the same code with clang like this:
clang -std=c99 -Werror=declaration-after-statement prog.c
it throws no errors.
Only if I compile the code with clang like this it throws the error I want:
clang -std=c90 -Werror=declaration-after-statement prog.c
prog.c:6:6: error: ISO C90 forbids mixing declarations and code [-Werror,-Wdeclaration-after-statement]
int i = 0;
^
1 error generated.
But this is not good for me because I need to use -std=c99.
Is it possible to force -Werror=declaration-after-statement along with -std=c99 when compiling with clang?
Looking at the source code of clang it seems like not supported.
The diagnostic is defined in clang/include/clang/Basic/DiagnosticSemaKind.td
def ext_mixed_decls_code : Extension<
"ISO C90 forbids mixing declarations and code">,
InGroup<DiagGroup<"declaration-after-statement">>;
And its only usage is in clang/lib/Sema/SemaStmt.cpp
StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
ArrayRef<Stmt *> Elts, bool isStmtExpr) {
const unsigned NumElts = Elts.size();
// If we're in C89 mode, check that we don't have any decls after stmts. If
// so, emit an extension diagnostic.
if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
// Note that __extension__ can be around a decl.
unsigned i = 0;
// Skip over all declarations.
for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
/*empty*/;
// We found the end of the list or a statement. Scan for another declstmt.
for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
/*empty*/;
if (i != NumElts) {
Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Diag(D->getLocation(), diag::ext_mixed_decls_code); // <-- here
}
}
...
Note the !getLangOpts().C99 in the if. The diagnose code will never execute with a standard above c90.
Well one thing you can surely try is build clang by yourself and delete that part of the if so end up with if (!getLangOpts().CPlusPlus).
I tried and it worked for me.
You can configure the clang build with cmake -G "Ninja" -DCMAKE_BUILD_TYPE="Release" -DLLVM_ENABLE_PROJECTS="clang" -DLLVM_TARGETS_TO_BUILD="X86" -DCMAKE_C_COMPILER="/usr/bin/gcc" -DCMAKE_CXX_COMPILER="/usr/bin/g++" -DLLVM_PARALLEL_LINK_JOBS=2 -DLLVM_OPTIMIZED_TABLEGEN=ON path/to/llvm-project/llvm
I'm compiling the below C code with gcc. No errors are thrown during compilation or at runtime. I ran through the code with gdb, and the answer given in sum is correct at the end, yet the printf() does not display anything on the screen. I've tried all sorts of combinations of fprintf(), printf(), and fflush(), but nothing works.
What do I need to change so the program will print the result to stdout?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num = 9;
int i, sum; i = 1, sum = 0;
while (i < 2 * num) {
sum = sum + i * i;
++i;
}
printf("sum: %d\n", sum);
fflush(stdout);
return 0;
}
The code is correct, and should print sum: 1785 for any conforming implementation.
This is a guess (update: which turns out to be correct), but ...
You've named the source file test.c, and you compile it with:
$ gcc test.c -o test
(or something similar) and execute it with:
$ test
which produces no output.
The problem is that test is a standard Unix command (and also a built-in command in some shells). When you type a command name to the shell, it first looks for built-in commands, then for executables in directories specified in your $PATH environment variable.
To execute a command in the current directory, prepend ./ to the name:
$ ./test
sum: 1785
$
This applies to any command in the current directory. There are so many built-in commands that you can't reasonably avoid colliding with them. Cultivating the habit of running executables in the current directory by typing ./whatever means that name collisions don't matter.
(Don't be tempted to add . to the front of your $PATH; that's dangerous. Think about what could happen if you cd into a directory and type ls, if there happens to be a malicious ls command there.)
There is nothing wrong with your program. It has to work. Try running it with redirection:
./a.out > myout
..and see if you get any output. If not, I'd suspect there is a problem with some kind of standard library mismatch.
Another option to check would be to build using SUN C compiler as opposed to gcc and see if that works. If it does, gcc is the culprit.
I am trying to debug the following C Program using GDB:
// Program to generate a user specified number of
// fibonacci numbers using variable length arrays
// Chapter 7 Program 8 2013-07-14
#include <stdio.h>
int main(void)
{
int i, numFibs;
printf("How many fibonacci numbers do you want (between 1 and 75)?\n");
scanf("%i", &numFibs);
if (numFibs < 1 || numFibs > 75)
{
printf("Between 1 and 75 remember?\n");
return 1;
}
unsigned long long int fibonacci[numFibs];
fibonacci[0] = 0; // by definition
fibonacci[1] = 1; // by definition
for(i = 2; i < numFibs; i++)
fibonacci[i] = fibonacci[i-2] + fibonacci[i-1];
for(i = 0; i < numFibs; i++)
printf("%llu ", fibonacci[i]);
printf("\n");
return 0;
}
The issue I am having is when trying to compile the code using:
clang -ggdb3 -O0 -Wall -Werror 7_8_FibonacciVarLengthArrays.c
When I try to run gdb on the a.out file created and I am stepping through the program execution. Anytime after the fibonacci[] array is decalared and I type:
info locals
the result says fibonacci <value optimized out> (until after the first iteration of my for loop) which then results in fibonacci holding the address 0xbffff128 for the rest of the program (but dereferencing that address does not appear to contain any meaningful data).
I am just confused why clang appears to be optimizing out this array when the -O0 flag is used?
I can use gcc to compile this code and the value displays as expected when using GDB....
Any thoughts?
Thank you.
You don't mention which version of clang you are using. I tried it with both 3.2 and a recent SVN install (3.4).
The code generated by the two versions looks pretty similar to me, but the debugging information is different. The clang 3.2 (which comes from a default ubuntu 13.04 install) produces an error when I try to examine fibonacci in gdb:
fibonacci = <error reading variable fibonacci (DWARF-2 expression error: DW_OP_reg operations must be used either alone or in conjunction with DW_OP_piece or DW_OP_bit_piece.)>
In the code compiled with clang 3.4, it all works fine. In neither case is the array "optimized out"; it's clearly allocated on the stack.
So I suspect the oddity that you're seeing has more to do with the emission of debugging information than with the actual code.
gdb does not yet support debugging stack allocated variable-length arrays. See https://sourceware.org/gdb/wiki/VariableLengthArray
Use a compile time constant or malloc to allocate fibonacci so that it will be visible to gdb.
See also GDB reports "no symbol in current context" upon array initialization
clang is not "optimizing out" the array at all! The array is declared as a variable-length array on the stack, so it has to be explicitly allocated (using techniques similar to those used by alloca()) when its declaration is reached. The starting address of the array is unknown until that process is complete.
I got the following error message while compiling the C code:
error: 'for' loop initial declarations are only allowed in C99 mode
note: use option -std=c99 or -std=gnu99 to compile your code
What does it mean?
How to fix it?
You have done this:
for (int i=0;i<10;i++) {
And you need to change it to this:
int i;
for (i=0;i<10;i++) {
Or, as the error says,
use option -std=c99 or -std=gnu99 to compile your code.
Update copied from Ryan Fox's answer:
gcc -std=c99 foo.c -o foo
Or, if you're using a standard makefile, add it to the CFLAGS variable.
You'll still need C99 if you want to mix statements and variable declarations. As other answers and the error message itself say, add -std=c99 to the command-line when you compile to enable C99 features [1].
But you have always been allowed to write a compound statement (a "block", IOW, but the standard never uses this word!) in place of a single statement.
#include<stdio.h>
int main() {
int i = 5;
{ /* new block, new declarations. */
int i;
for (i=0;i<10;i++){
}
}
printf("%d\n", i); /* prints "5\n" */
}
This is legal in K&R, C90 (aka C89, it's the same thing), and C99.
Enabling C99 mode gets you lots of cool stuff, but it also disables some other cool stuff that gcc allows by default, like anonymous structures and unions within structures and unions.
-std=gnu99 probably enables "all the goodies", but I caution you to avoid doing this. It will make unnecessary difficulty if you (or others) wish to port the code. I'd probably have a windows version of my pet project, ported for free by somebody, had I not done this very thing. It ties you gcc. You don't want to be tied. That's the whole bloody point of standards.
The other answers give you a work around to deal with GCC's default mode. If you'd like to use C99, (which I do recommend in general) then you have to add that compiler flag:
gcc -std=c99 foo.c -o foo
Or, if you're using a standard makefile, add it to the CFLAGS variable.
It means you can't declare variables in for statement.
You should do:
int i ;
for( i = 0 ; i < len ; i++ )
What you are probably doing
for( int i = 0 ; i < len ; i++ )
I'm trying to solve the 3n+1 problem and I have a for loop that looks like this:
for(int i = low; i <= high; ++i)
{
res = runalg(i);
if (res > highestres)
{
highestres = res;
}
}
Unfortunately I'm getting this error when I try to compile with GCC:
3np1.c:15: error: 'for' loop initial
declaration used outside C99 mode
I don't know what C99 mode is. Any ideas?
I'd try to declare i outside of the loop!
Good luck on solving 3n+1 :-)
Here's an example:
#include <stdio.h>
int main() {
int i;
/* for loop execution */
for (i = 10; i < 20; i++) {
printf("i: %d\n", i);
}
return 0;
}
Read more on for loops in C here.
There is a compiler switch which enables C99 mode, which amongst other things allows declaration of a variable inside the for loop. To turn it on use the compiler switch -std=c99
Or as #OysterD says, declare the variable outside the loop.
To switch to C99 mode in CodeBlocks, follow the next steps:
Click Project/Build options, then in tab Compiler Settings choose subtab Other options, and place -std=c99 in the text area, and click Ok.
This will turn C99 mode on for your Compiler.
I hope this will help someone!
I've gotten this error too.
for (int i=0;i<10;i++) { ..
is not valid in the C89/C90 standard. As OysterD says, you need to do:
int i;
for (i=0;i<10;i++) { ..
Your original code is allowed in C99 and later standards of the C language.
#Blorgbeard:
New Features in C99
inline functions
variable declaration no longer restricted to file scope or the start of a compound statement
several new data types, including long long int, optional extended integer types, an explicit boolean data type, and a complex type to represent complex numbers
variable-length arrays
support for one-line comments beginning with //, as in BCPL or C++
new library functions, such as snprintf
new header files, such as stdbool.h and inttypes.h
type-generic math functions (tgmath.h)
improved support for IEEE floating point
designated initializers
compound literals
support for variadic macros (macros of variable arity)
restrict qualification to allow more aggressive code optimization
http://en.wikipedia.org/wiki/C99
A Tour of C99
if you compile in C change
for (int i=0;i<10;i++) { ..
to
int i;
for (i=0;i<10;i++) { ..
You can also compile with the C99 switch set. Put -std=c99 in the compilation line:
gcc -std=c99 foo.c -o foo
REF: http://cplusplus.syntaxerrors.info/index.php?title='for'_loop_initial_declaration_used_outside_C99_mode
For anyone attempting to compile code from an external source that uses an automated build utility such as Make, to avoid having to track down the explicit gcc compilation calls you can set an environment variable. Enter on command prompt or put in .bashrc (or .bash_profile on Mac):
export CFLAGS="-std=c99"
Note that a similar solution applies if you run into a similar scenario with C++ compilation that requires C++ 11, you can use:
export CXXFLAGS="-std=c++11"
Jihene Stambouli answered OP question most directly...
Question was;
why does
for(int i = low; i <= high; ++i)
{
res = runalg(i);
if (res > highestres)
{
highestres = res;
}
}
produce the error;
3np1.c:15: error: 'for' loop initial declaration used outside C99 mode
for which the answer is
for(int i = low...
should be
int i;
for (i=low...
Enable C99 mode in Code::Blocks 16.01
Go to Settings-> Compiler...
In Compiler Flags section of Compiler settings tab, select checkbox 'Have gcc follow the 1999 ISO C language standard [-std=c99]'
I had the same problem and it works you just have to declare the i outside of the loop:
int i;
for(i = low; i <= high; ++i)
{
res = runalg(i);
if (res > highestres)
{
highestres = res;
}
}
For Qt-creator: just add next lines to *.pro file...
QMAKE_CFLAGS_DEBUG = \
-std=gnu99
QMAKE_CFLAGS_RELEASE = \
-std=gnu99