How do I get GCC to work? - c

I am using Vim as my editor and GCC as my compiler, but it’s not working quite right. Let‘s say I am making a basic program to determine if a number is odd or even. Here is my code:
#include <stdio.h>
int main(int argc, char argv[])
{
int i;
printf("Enter a number: ");
scanf("%d\n", &i);
printf("%d\n", i);
if(i % 2 == 0)
{
printf("Your number is even.\n");
}
else if(i % 2 != 0)
{
printf("Your number is odd.\n");
}
else
{
printf("Invalid input.\n");
}
getchar();
return 0;
}
I'm not sure if I am programming this wrong, or gcc is just not a good compiler, or whatever. I am running linux, which I dual boot with windows. Now I press ctrl-d to stop the process, and only then does it print me back my number, and tell if it is odd or even. It isn't just this one, a lot of other programs with similar formats seem to do this to.
~ $ ./test
Enter a number: 45
45 //I press enter, nothing happends. Ctrl-d
Your number is even. //ctrl-d again
~ $
So what I'm asking is, is there a way to program it so that I don't have to quit the program in order for it to work, or is there another compiler that wouldn't have this problem? I am running on Ubuntu 14.04 dual booted with Windows 8.1.

\n in the format for scanf means "read until hit into non-whitespace character and then ignore them". Remove it and make the format for reading "%d".

to get gcc to work from vim,
goto the vim command prompt
shell gcc <and all needed parameters>
Or open another command window
set it to the same directory as the program being edited
gcc <and all needed parameters>
in general, try to make the compile step separate from the link step. I.E. to compile:
gcc -c <mySource.c> -Wall -Wextra -pedantic -std=c99 -o mySource.o
if any header files, other than those in the default 'include' path then add
-I<pathToHeaderFile>
which is often in the same directory so would be:
-I.
then link with:
gcc mySource.o -o mySource
You can add the -ggdb parameter to both lines if you plan on doing any debugging.
to add any library directories then on the link step append
-L<pathToLibrary>
to add any libraries then on the link step append, after any library parameters:
-l<shortLibName>
The initialization file for vim can contain the necessary info to invoke gcc by some keystroke combination, but I'm not totally familiar with the details.

Related

[msys2][gcc] Wrong output of wprintf() compiling with MSys2's gcc 10.2

I need to get this stripped-down C program working on Windows 7 using MSys2's gcc toolchain:
#include <stdio.h>
void wmain(int argc, wchar_t *argv[])
{
for (int i = 1; i < argc; i++)
wprintf(L"%s\n", argv[i]);
}
The code compiles with
gcc -Wall -municode -O2 -march=x86-64 -m64 test.c
but gives me the following output
>> ./a.exe kk лл
k (!)
:?:?
I have the following questions:
What am I doing wrong?
How would I downgrade the compiler to
version, say, 9.x, or 10.1? (I'm under the impression that the very
same program compiled about one year ago used to work correctly)
Edit [1]: Meanwhile I managed to set up a new MSys2 environment using gcc 9.3. The "error" persists, so it's not the compiler.
Edit [2]: "Some programmer dude" (cmp. below) described the "immediate" solution (THX!).
Even for the wide-character wprintf the format %s is for narrow character strings.
You need to use %ls to print wide-character strings:
wprintf(L"%ls\n", argv[i]);
However this might still not be enough, as the actual encoding of the input (including arguments) might not be what's expected. You need to take into account the encoding used by the terminal the program is running in.

Function printf() to print backspace problem

There are two programs and they get different results, but I don't understand why.
Here is the first:
int main()
{
printf("12345");
fflush(stdout);
printf("\b\b");
fflush(stdout);
return 0;
}
The result is: 123.
Then the second:
int main()
{
printf("12345");
fflush(stdout);
sleep(1);
printf("\b\b");
fflush(stdout);
return 0;
}
but the result is: 12345.
Why does the sleep call make the second result different when I expect a "123" result?
The code was running in the CLion.
and My OS is macOS, if it matters.
Depending on the Terminal, '\b' might "erase" a character or only move the cursor to the left. To have a foolproof solution, use:
#include <unistd.h>
#include <stdio.h>
int main(void)
{
printf("12345");
fflush(stdout);
sleep(1);
printf("\b\b \b\b");
fflush(stdout);
}
Your code first displays "12345" and then displays "123". Without the sleep, the "12345" is displayed for too little time to be visible. With the sleep, you can see the "12345" for about a second before the "4" and "5" are erased.
With the original code (called bs97, compiled from bs97.c), and with my command line prompt Osiris JL:, I get the output:
Osiris JL: bs97
123Osiris JL:
Note that the new prompt has overwritten the 45. You can see that if you add putchar('\n'); after the second fflush(). (I added void to int main(void) to avoid compilation warnings (errors) with my default compilation options.)
Osiris JL: make bs97 && bs97
gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes bs97.c -o bs97
12345
Osiris JL:
This time, the 4 and the 5 are still visible.
Simply using backspace does not erase the content that was previously there; it positions the write position on screen back one place, that's all. If you want to erase what was there, you need to output printf("\b \b\b \b") to go back, output a space, and go back again — repeated twice. Or you could use printf("\b\b "), but that would leave the write position after the two spaces; or you could use printf("\b\b \b\b") to leave the write position after the 3. And there are other variations on this theme.
With the second program with the sleep, I get similar behaviour, except that the 12345 is on display while the program sleeps.
I'm testing on a Mac running macOS 10.14 Mojave, using a home-built GCC 8.2.0 or the clang compiler from XCode 10.0.

Why the charater "%" is printed after performing a printf without "\n"?

Here is my simple c code. Can anyone tell me why it gives me this output?
I am coding on an arch linux 4.15.1-2-ARCH machine with the gcc compiler (version: 7.3.0)
I compile with: gcc --std=c99 -Wall --pedantic client.c -o client
I have the following code:
#include <stdio.h>
int main(void) {
printf("Test.");
return 0;
}
But it get the following Output:
Test.%
I don't know where the % is comming from. Would be great if someone can give me a hint.
Your printf string doesn't contain a newline character. As a result, whatever string your shell normally prints as a prompt will appear immediately after what your program prints.
Running on my machine:
$ ./x1
Test.$
My prompt is "$", so that's what appears after the string
Adding \n, which is the escape sequence for a newline, to your string will make your prompt appear on the following line:
printf("Test.\n");
Output:
$ ./x1
Test.
$
Try:
printf("Test.\n");
The word Test. printed by your program probably joined with the first character of your terminal prompt. Adding a \n will print a new line character, so your terminal prompt will be written on the next line when your program exits.

GCC/Command Prompt error: '.' is not recognized as an internal or external command

I'm fairly new to C and am completely new to using the command prompt and GCC to compile and run my programs. I'm struggling to find the right words to ask this question properly so please bear with me, I am doing my best.
I need to use GCC to compile and run this C program but I'm getting an error that I do not understand. In this example program, I was told to use these lines to compile and run the code:
$ gcc -Wall -std=c99 -o anagrams anagrams.c
$ ./anagrams dictionary1.txt output1.txt
So that is what I did. GCC does compile the program file, so the first line does not give me any error. But GCC does not like the second line, as shown below:
C:\Users\...\Example>gcc -Wall -std=c99 -o anagrams anagrams.c
C:\Users\...\Example>./anagrams dictionary1.txt output1.txt
'.' is not recognized as an internal or external command,
operable program or batch file.
Everywhere I look, it says to use "./filename" to run the program after compiling so I don't understand why it is not working for me. Any help or advice would be really appreciated.
Also, here is the main() of the program to show why those two .txt files are needed:
int main(int argc, char *argv[])
{
AryElement *ary;
int aryLen;
if (argc != 3) {
printf("Wrong number of arguments to program.\n");
printf("Usage: ./anagrams infile outfile\n");
exit(EXIT_FAILURE);
}
char *inFile = argv[1];
char *outFile = argv[2];
ary = buildAnagramArray(inFile,&aryLen);
printAnagramArray(outFile,ary,aryLen);
freeAnagramArray(ary,aryLen);
return EXIT_SUCCESS;
}
'.' is not recognized as an internal or external command
This is not a GCC error. The error is issued by the shell when trying to run a command.
On Windows this
./anagrams dictionary1.txt output1.txt
should be
.\anagrams dictionary1.txt output1.txt
as on Windows the path delimiter is \ as opposedto IX'ish systems where it is /.
On both systems . denotes the current directory.
The reason for the crash you mention in your comment is not obvious from the minimal sources you show. Also this is a different question.

printf doesn't work, even with newline and fflush()

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.

Resources