Some problems when trying to implement C code on Visual Studio Code - c

I recently started doing some programming with C/C++. I was using Dev-C++ and today
i changed to Visual Studio Code because later on i'll need to work in other programming languages too, like Python, R etc. I successfully installed it and i added the extensions of C/C++ and Code runner. Although am having some problems when i try to run the following two basic programs:
#include <stdio.h>
int main(void){
printf("hello world\n");
return 0;
}
and
#include <stdio.h>
int main(void){
int x;
printf("Give a number: ");
scanf("%d",&x);
printf("Your number is: %d\n",x);
return 0;
}
In the first program i get the following output in the integrated terminal of VS code:
My first question is a matter of appearance, how can i remove the path that shows above the "hello world" output? Also, notice that i am on the terminal option, if i switch to the output option, nothing is being displayed there, although i have seen in some tutorials that they can display their results in the output option which is more minimalistic than the terminal, in addition it displays the run time of the program which is a nice feature.
In the second program when i press the Run Code button it opens my cmd first and asking to give a number, after i give the number and press Enter i can type the asked number also in the integrated terminal of VS and get the result. Is there anyway to surpass my cmd? I.e. to run the program only in VS without running it also through the cmd? Note that i have already checked the option "Run In Terminal" in the settings of the code runner extension.
Thanks in advance!

So I believe you are on windows, simply installing the extension wont help, there are a few more steps to this.
You'll create a tasks.json file to tell VS Code how to build (compile) the program. This task will invoke the g++ compiler to create an executable file based on the source code.
From the main menu, choose Terminal > Configure Default Build Task. In the dropdown, which will display a tasks dropdown listing various predefined build tasks for C++ compilers. Choose g++.exe build active file, which will build the file that is currently displayed (active) in the editor.
This will create a tasks.json file in a .vscode folder and open it in the editor.
Your new tasks.json file should look similar to the JSON below:
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "C/C++: g++.exe build active file",
"command": "C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\g++.exe",
"args": ["-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe"],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": ["$gcc"],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
To run the build task defined in tasks.json, press Ctrl+Shift+B or from the Terminal main menu choose Run Build Task.
You can run your program in the terminal by typing .exe (or .<your program name.exe if you use a PowerShell terminal).

Hello you should try to install the Code Runner extension. You will run your future C and Python code easily.

Related

VS Code debugging fails when there's a space in the source path

I'm trying to create a GDB debugging pipeline for my c files in VS Code (windows). You can find my tasks.json and launch.json below.
Now if the path to my source file(s) doesn't contain any spaces this works fine. However, if it does include spaces I will receive a message like this whenever the debugger tries to break:
This is because the source file it's looking for is actually located at
E:\Libraries\Dropbox\UNI\Semester 5\test.c
And I'm guessing either GDB has sent VS Code a bad link to the file, or VS Code doesn't understand spaces in it's file paths (which I doubt). Sorry but I don't really understand the link between GDB and VS Code during the debugging session.
Does anyone know how to fix this?
tasks.json:
{
"version": "2.0.0",
"tasks": [
{
"label": "Build C Program",
"type": "shell",
"command": "gcc",
"options": {"cwd": "${fileDirname}"},
"args": [
"-g", "-o", "${fileBasenameNoExtension}.exe", "${fileBasename}"
],
"group": {"kind": "build","isDefault": true}
}
]
}
launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"miDebuggerPath": "C:\\cygwin64\\bin\\gdb.exe",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "Build C Program"
}
]
}
I think the latest version of VS Code may have already solved this issue. However, some knowledge about how command line arguments work might help you understand the cause of this problem.
Basically, shells split words separated by whitespaces and treat these words as stand-alone arguments. For files with no embedded spaces in their paths, everything's okay. For files with embedded spaces in their paths, it takes some extra typing to walk around the pitfall.
Say we want to compile a file named pathWithNoEmbeddedSpaces.c, we simply type:
gcc -g -o target1.exe pathWithNoEmbeddedSpaces.c
Command line arguments separated by whitespaces, from gcc, -g to pathWithNoEmbeddedSpaces.c in the above case, are treated as stand-alone arguments. They are then passed by the shell to GCC, our compiler, which understands that we want to compile 1 source file.
Say we want to compile another file named path With Embedded Spaces.c, we type:
gcc -g -o target2.exe path With Embedded Spaces.c
How many stand-alone arguments do we have this time? 8! Now, the shell treat gcc ... path With Embeded Spaces.c all as stand-alone arguments. GCC is confused since what it sees is a requirement to compile 4 source files, which may not even exist in the current directory!
As for the solution, quotation marks come to the rescue, which is also known as quoting. Most shells are fine with both single quote (') and double quote ("). But you may want to check out the details for your shell. Whenever there are embedded spaces in the file path, use the quotation. Such as:
gcc -g -o target2.exe "path With Embedded Spaces.c"
The shell now knows that path With Embedded Spaces.c is one argument and should be treated as a whole, which is then passed to GCC for compilation to be done.
Now, what does VS Code have to do with the issue?
In the "Ancient Times" of VS Code, it simply replaces predefined variables such as ${fileDirname} in your JSON files, then joins the arguments separated by spaces, and passes the command to the underlying shell. Even though VS Code performs special treatment when it comes to commands and arguments that contain spaces or other special characters, it doesn't go over the replacements for predefined variables. So ${fileBasename} gets replaced without quotation.
Assume our current working directory is E:\Libraries\Dropbox\UNI\Semester 5, then VS Code will replace ${fileBasename} by test.c and ${fileDirname} by E:\Libraries\Dropbox\UNI\Semester 5:
gcc -g -o test.exe test.c
The compilation should be performed without any issue, since test.c is in the current working directory. However, condiser the target path in launch.json:
"program": "${fileDirname}\\${fileBasenameNoExtension}.exe"
GDB will search for a program named E:\Libraries\Dropbox\UNI\Semester since no quotation is used, and then exit abnormally because there isn't such a program.
To cope with file path with embedded spaces, consider use quotations. For example, you could surround predefined variables with single quotation marks: '${fileDirname}', '${fileBasename}', etc. Several lines in your JSON files should look like these examples:
"-g", "-o", "'${fileBasenameNoExtension}.exe'", "'${fileBasename}'"
"-g", "-o", "\"${fileBasenameNoExtension}.exe\"", "\"${fileBasename}\""
"program": "'${fileDirname}\\${fileBasenameNoExtension}.exe'"
However, as a general rule, avoid spaces in paths for source files when every possible.

Windows gui C build system in sublime text

I had linker error: undefined reference to windows.h functions like textout,selectobject,beginpaint. But I was able to remove the error
by adding "-mwindows" in sublime build system. But now im not able to get any output in windows terminal. Eg: if i try to use printf("test"); it won't show any output in windows terminal and textout() will only output textout string in gui window.
I tried it with codeblocks and it was able to get output of printf in windows terminal and textout in another window.
Is there anyway i can make sublime build system do the same?
{
"cmd": ["gcc", "-Wall","-mwindows","-pedantic-errors", "$file_name","-o", "${file_base_name}.exe", "&&", "start", "cmd", "/k" , "$file_base_name"],
"selector": "source.c",
"working_dir": "${file_path}",
"shell": true
}
If you want to build a console application, then you need to also add the -mconsole option to your compiler command line.
That will give you a Windows application that automatically creates and runs in the context of a console (text-based environment).
If you just pass -mwindows, then you get a standard Windows application that expects to have a GUI. You (your code) is responsible for creating a window and outputting text/graphics to that window. It doesn't happen automatically.

A program in C language made by CodeBlocks IDE runs with a double-click in Windows but not in Ubuntu. why?

I am learning C. I am using Ubuntu as main OS but I also have Windows 7 for testing in another partition. I have made a program in C in both OSes using Code Blocks. When I double click the compiled file of program in windows it runs, but when I do the same in Ubuntu it does not run. I have also created .desktop file for it, but even then it doesn't run. But using the command.someone told me code GUI in.so how can i code GUI in it? also why it runs on windows?
./addition
makes it run in terminal. But I want to run it using GUI. I am clicking on its icon but its not opening.Do i need to code GUI for it?
source code is
#include <stdio.h>
int main(){
int a,s,d;
printf("type the values u want to add and give tab between them\n");
scanf("%d %d",&a,&s);
d=a+s;
printf("addition is %d",d);
system("read -p 'Press Enter to EXIT...' var");
return 0;
}
in linux if you run a shell program from the desktop, it does not have a std input or output attached. For this reason you cannot see anything about it.
A quick solution would be to open a terminal and run it from there.
Two easy options if you don't know how to run the program from terminal:
A) Drag the icon of the program into the terminal, it will automatically build the full path to run it
B) Move to the program's home folder and run it from there "./programName"
I hope this helps mate.

How to build and run C programs in sublime text 3 mac osX

I have installed sublime text 3 and a package control for it. Now I'm trying to build my hello-world.c but I cannot build it. When I open tools --> build with.. it offers me C++ single file but I want to build my program with C. There is no C alternative in the build systems menu.
First create your file :
/* hello.c */
#include <stdio.h>
int main() {
printf ("Hello world!\n");
return 0;
}
save it something like hallo.c then compile it with gcc. So open your terminal go in your directory fileand type gcc hallo.c -o hallo and run ./hallo
To buit it on sublime plese do this :
In Sublime, click Tools -> Build System -> New Build System...
{
"cmd" : ["gcc", "-o", "$file_base_name", "$file_name"],
"cmd" : ["./$file_base_name"],
"selector" : "source.c",
"shell" : false,
"working_dir" : "$file_path"
}
Or here
Goto tools > Change build system
Anyway, I suggest you use an IDE or much better use just file & compilator.
Sublime text is just and IDE.
Install a C compiler and build and run using that compiler.
Try some sublime plugin compiler.

First steps in Eclipse

I try to figure out Eclipse by writting a HelloWorld.c from scratch and hope that you can give me some help concerning the problems I face.
When launching Eclipse, I select the standard workspace.
In the Project Explorer, I create a new C project, called HelloWorld. Settings are "Empty Project" and "MinGW". Next: Debug and Release activated. Finish.
In the Menu toolbar "Window->Preferences", I make sure that under "General->Workspace" the "Text File Encoding" is set to UTF-8 and "New Text File Line Delimiter" to Unix. Apply and OK. Again under "Window->Preferences->C/C++->New C/C++ Project Wizard", under "Toolchains" I select "MinGW GCC". "Make Toolchain(s) preferred", "Apply", and "OK".
Now all the necessary setings for this C project are saved in a settings file in the project folder - if I understand this right.
In the Project Explorer, ther HelloWorld Project contains now a header-folder with three subfolders (C:/MinGW64/lib/gcc/x86_64-w64-mingw32/someversion/include and .../include-fixed, and C:/MinGW64/x86_64-w64-mingw32/include).
I create a new C Source File with explicit name "HelloWorld.c" and I get a nice window with lines to write any desired code and also an outcommented "HelloWorld.c"-title on top.
So I write
#include <stdio.h>
main(){
printf("Hello World!");
return 0;
}
and save it. So far, so good.
Now, I press "Build All" and get a Warning "return type defaults to 'int' [-Wreturn-type]".
When I press "Debug", I get the message "Info:Nothing to build for HelloWorld" but when I press "Run", the Console shows "Hello World!" anyway.
In previous (very same) projects, I already got error messages like "Launch failed. Binary not found." which disappeard after many times pressing "Build All" and "Run". And also the error message "Program file does not exist." although I just wrote and saved the above C Source File code. I could not solve it, deleted the Project, restarted Eclipse and did all again as explained above.
What did I or am I doing wrong?

Resources