Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I installed the GCC compiler to write some C code, but when I navigate to the directory, and use the command gcc -o helloworld helloworld.c It makes an executable on my desktop like normal, but when I run it, the executable closes immediately
I don't think that the code is the problem, but it's a possibility.
#include <stdio.h>
int main()
{
printf("Hello world\n");
return 0;
}
The problem is that Windows has poor support for running non-GUI programs.
A common way to run a program under Windows is to double-click the executable from an explorer window. For a program like yours that just prints to standard output, this will open a new window for the program's output, the program will run and quickly finish, and Windows will immediately close the window, perhaps before you have a chance to see it.
A common workaround is to add something to the end of your program, such as a call to getchar(), to cause the program to wait for input.
Another solution is to run the program from a command prompt. Its output will then appear in the current window rather than in a temporary one, and you'll see the program's output followed by a new prompt. If you run it that way, and added getchar() is unnecessary, and will make the program wait for input before terminating.
The Windows OS emphasizes GUI programs rather than programs that use plain text input and output. C was developed in a different kind of environment (though of course implementations of C for Windows support graphical operations).
You have missed this line getchar() in your code.
#include <stdio.h>
int main()
{
printf("Hello world\n");
getchar();
return 0;
}
Note: Though, this is not the fix as #Keith Thompson explains in the other answer. Instead, this is a way where you can force the program from exiting until it waits for a keypress before the console window exits.
Another way (without using getchar())
Open the Command Prompt (cmd.exe), and navigate to the program's directory and run your program from there. You'll find that the window doesn't disappears anymore, rather it stays open.
Related
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int a;
scanf("%d", &a);
printf("%d", a);
system("pause");
return 0;
}
Using the 'scanf', the console does not open properly. The visual studio code is too difficult. This is the first code. Please help me set the environment.
Does it answer your question?
system("pause"); - Why is it wrong?
Using system("pause"); is Ungood Practice™ because
It's completely unnecessary. To keep the program's console window open
at the end when you run it from Visual Studio, use Ctrl+F5 to run it
without debugging, or else place a breakpoint at the last right brace
} of main. So, no problem in Visual Studio. And of course no problem
at all when you run it from the command line.
It's problematic & annoying when you run the program from the command
line. For interactive execution you have to press a key at the end to
no purpose whatsoever. And for use in automation of some task that
pause is very much undesired!
It's not portable. Unix-land has no standard pause command.
The pause command is an internal cmd.exe command and can't be
overridden, as is erroneously claimed in at least one other answer.
I.e. it's not a security risk, and the claim that AV programs diagnose
it as such is as dubious as the claim of overriding the command (after
all, a C++ program invoking system is in position to do itself all
that the command interpreter can do, and more). Also, while this way
of pausing is extremely inefficient by the usual standards of C++
programming, that doesn't matter at all at the end of a novice's
program.
So, the claims in the horde of answers before this are not correct,
and the main reason you shouldn't use system("pause") or any other
wait command at the end of your main, is the first point above: it's
completely unnecessary, it serves absolutely no purpose, it's just
very silly.
I created a simple C program a while ago. It's a simple command-line generator that takes some number, prints the results and stops. I always ran it in the editor's command line enviroment that automatically paused after the program ran, so I omitted adding a getchar() at the end.
I now regret this, because I managed to lose the source. All I have now is the complied .o and .exe file, and the latter - of course - exits immediately after it prints the output, so it's unusable. It wasn't that long, about 100 lines, but I'd like to avoid rewriting it. (Also, I might even learn something new from this way.)
Now I have very basic knowledge of C, and about zero on computer-degree x86 assembly (though I learnt the basics of 8086-assembly for microcontrollers, it won't be that helpful now I guess), so I'm kinda stuck here. Can I either add that getchar() like pausing function to the complied code, or is there any way I can make that .exe stop before exiting while still keeping it standalone?
The program will run on a Windows 10 system.
I would write some sort of batch script in which you call your program and then just run pause, which waits for you to hit a key before it continues.
wrapper.bat:
yourprogram.exe
pause
Of course you can disassemble your executable into raw x86 assembly code, then look up the code for a simple getchar() on Windows, add that and reassemble. However, it would probably be less time consuming to rewrite the program, depending on how complex it was or just create a wrapper batch-script.
It's possible to hijack .o file, you can even do it with .exe, .dll, ... but it's not simple and requires a lot of know-how. What I would suggest is to use some sort of decompiler to try to restore the original source code, make the change and compile it again. You can find suggestions of decompilers in this old answer.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to create a program in C such that it compiles another program of c and saves the output in a text file. For example, I want the output of my "input.c" file to be stored in a text file named "output.txt", using a C program. Please help.
I have chosen this project because it often becomes difficult to copy the entire output screen in Turbo C++, and sometimes turbo c doesn't show the entire output and only the current output screen is copied, leaving behind the previous output.
It's possible. You either run a shell command that compiles and runs your subprogram (man 3 system, easy), or you go with more advanced techniques such as on-the-fly compilation (http://blog.coldflake.com/posts/On-the-fly-C++/ or https://bellard.org/tcc/ if you're a C programmer)
You want to look at the Standard C functions named system() and POSIX popen().
On a POSIXly system with a C compiler, to compile a simple C program would be
system("cc -o input input.c");
And to run it and capture the output,
FILE *fp_in = popen("./input", "r"); /* to read */
FILE *fp_out = fopen("output.txt", "w"); /* to write */
Then read from fp_in and write to fp_out. That's the basic idea. I've left the details for you to figure out, so you gain deep insight into deep C secrets :-)
Don't forget the error handling for all library functions.
PS: If the system's shell supports redirection, you might even simplify the popen/fopen combo to a single system("./input > output.txt");
PPS: If the PS works, you might as well combine everything into system("cc -o input input.c && ./input > output.txt"); I trust you know how to wrap this in main().
The C11 standard (read n1570) does not define how to run a compiler. In many cases (think about cross-compiling for some Arduino target) you won't be able to run a compiler on the target machine (it could be "too small").
BTW, you could compile your code into some executable, remove every compiler from your system, and run that executable (in a situation where your system don't have any compiler)....
The C11 standard vaguely speaks in §7.22.4.8 of a system function.
On some implementations, that system function is able to start other programs (in processes) thru some unspecified command processor. But there is no guarantee that you'll be able to start a compiler (for example, you could run your executable on a Windows computer without any compiler).
(In practice, your computer is likely to practically have some command line C compiler, but you need to know which one and how to invoke it)
On POSIX, you could use system(3) (which uses /bin/sh -c), but also fork(2) & execve(2) -and other functions, e.g. popen(3)- to start other programs.
On Linux, you usually have some command line compiler, often GCC as gcc (or even cc). You could run it (e.g. using system).
I like to do the following trick on my Linux system: generate some temporary file containing C code, e.g. /tmp/temporaryc.c, then compile that temporary file into some temporary plugin /tmp/temporaryplugin.so by using system with a command (in a string built at runtime) like gcc -Wall -O -fPIC -shared /tmp/temporaryc.c -o /tmp/temporaryplugin.so, and at last dynamically load that plugin using dlopen(3).
Look also into JIT-compilation libraries like libgccjit.
BTW, you should consider giving up Turbo C (it is an obsolete compiler for obsolete variants of C or C++) and switch to Linux on your PC.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Ok. So I'm trying to write a shell like application to run in the Ubuntu terminal but I don't know where to start. I need to write a C program in a text editor, run the program in the existing terminal (ioana#ioana-VirtualBox:~/Desktop$ gcc OS.c -o OS.c and than ./OS).
My C program should reset the terminal and let me remake and/or somehow import the basic function from the original shall(I should write an exit function that will close the terminal, but it should not be mistaken with the exit from the original shall of the terminal; make the buffer for key UP-DOWN history that won't be mistaken with the one already implemented). I read a bit about ncurses library and also installed it.
All I have so far is this:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "ncurses.h"
int main()
{
system("reset");
return 0;
}
It's a perfect running code and it clears the screen but if I press UP or DOWN, the previous commends are displayed and if I type exit the terminal closes. I don't want any of these.
I'll be pretty grateful if someone can explain what I can do. I read about those subjects but didn't manage to find something that I can clearly understand.
Several issues and hints:
read first Advanced Linux Programming (a book, also freely available online) to learn more about how to use system calls (listed in syscalls(2)...). Use strace(1) to discover what system calls are done by some programs (so try strace date then strace -f bash -c 'date; pwd'...). Read about credentials(7).
fork(2) & execve(2) & waitpid(2) are the basics of every shell; see my hints here. But they are difficult to understand. If you want to have command pipelines, you'll also need pipe(2), dup2(2), close(2); for redirection, you'll also need open(2)
understand what globbing is. See glob(7) and the references there.
terminals are in fact ttys, demystified here. For historical reasons, they are complex. See termios(3)
history and command line editing and auto-completion are well handled with the GNU readline library; full screen console-like editing (à la emacs or vi) would need the ncurses library; but it is not the essential part of a shell.
job control can be tricky. Read about process groups. See getpgid(2) & setsid(2)
all Linux shells are free software, so please study their source code. The sash shell has few features (and some bugs!), but its source code is small and easy to read. GNU bash, zsh, fish have more features so are more complex.
The system(3) library function is forking itself a /bin/sh shell, so using it in your own shell is somehow cheating.
PS. If you are new to all that, making a full-featured shell would take several months.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm making an application that will create a working executable based on what the end-user inputs into the program.
For example:
if (make_annoying_sounds == true)
{
//Generates an executable that makes annoying beeping sounds
}
else
{
//Generates an executable that doesn't make annoying beeping sounds
}
Basically I want my program to generate/create another program. I've seen/used many programs that do this. I have searched all over the internet and can't find anything. All help is appreciated. (Create a program, from within my program).
Try using a basic system call to invoke a compiler after you've created the source file.
You can create the source file with just the utilities found in stdio.h
Security Note: The system function is known to be dangerous. When in doubt, call a function like exec to invoke the compiler. Although exec erases the currently running process, so you should use fork and then call exec if you want to keep doing stuff after the compilation has finished.
So you want to create a compiler? This question below contains a whole list of resources to help you get started.
Learning to write a compiler
You need to do the following:
Based on the user input, generate the code for the custom program.
Compile that code into an executable file.
Theorically, you could, depending on what the user inputs, make your C code generate C-code inside your if statements. However this would be quite difficult.
The best way I think is to make an independent C engine which will only implement functions that any of the generated program can execute (playing the sound given in parameter, for example). The program you are trying to code (not the engine, but the one with the if statements, let's call it the "master program") must generate code which implements the algorithm which will choose what function of the engine to call and when. This generated code should be written in a scripting language like lua, since in is easier to generate script code than C. Thus, the engine should be designed to be able to communicate with Lua scripts. When the user clicks on the final "generate program" button of the master program, the master program calls gcc to compile the engine and the Lua script to generate the program the user tried to create. This is long, but this is, I think, the right way to do it.