I have started using Visual Studio Code on Kali Linux 2019.4. I am compiling C code using the Code Runner extension. I am experiencing an issue where arguments passed to the application via "args": ["String1", "String2"] in launch.json, are not getting passed to the application as is indicated in the below output:
Output:
[Running] cd "/home/user/Desktop/test/" && gcc test.c -o test && "/home/user/Desktop/test/"test
Length of argv is: 1
Arg 1 is: /home/user/Desktop/test/test
Arg 2 is: (null)
Arg 3 is: GJS_DEBUG_TOPICS=JS ERROR;JS LOG
Missing argument
[Done] exited with code=1 in 1.166 seconds
What could be the reason that the arguments are not getting passed? I have included the C code and launch.json contents below:
C code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
printf("Length of argv is: %d\n", argc);
printf("Arg 1 is: %s\n", argv[0]);
printf("Arg 2 is: %s\n", argv[1]);
printf("Arg 3 is: %s\n", argv[2]);
if (argc < 3)
{
printf("Missing argument\n");
exit(1);
}
printf("Arg 1 is %s\n", argv[1]);
printf("Arg 2 is %s\n", argv[2]);
return 0;
}
launch.json:
"version": "0.2.0",
"configurations": [
{
"name": "gcc build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": ["String1","String2"],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "gcc build active file",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
If you update your code runner executor map settings inthe extensios' settings.json to from
"gcc cd $dirName $fileName -o $fileNameWithoutExt && $dirName$fileNameWithoutExt"
To: (remove $dirname)
"gcc $fileName -o $fileNameWithoutExt && $fileNameWithoutExt arg1 arg2 arg3 .. etc"
Related
I am using VSCode to run multiple C files, but VSCode doesn't seem to read the header files properly:
My hello.c file in project/src/hello.c file looks like this
#include <stdio.h>
#include "hellofunc.h"
int main(int argc, char* argv[]) {
//body
}
The referenced hellofunc.h file is in project/include/hellofunc.h
However, when I run hello.c in VSCode, I get the following error:
"[PATH]/project/src/"hello
hello.c:2:10: fatal error: 'hellofunc.h' file not found
My c_cpp_properties.json file looks like this:
{
"configurations": [
{
"name": "Mac",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [],
"macFrameworkPath": [
"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks"
],
"compilerPath": "/usr/bin/clang",
"cStandard": "c17",
"cppStandard": "c++17",
"intelliSenseMode": "macos-clang-x64",
"configurationProvider": "ms-vscode.makefile-tools"
}
],
"version": 4
}
I know I need to add the file path to the project/include folder somewhere, but I haven't been able to figure out where. Can someone help? Thanks!
I'm trying to print all of system's groups (Ubuntu 20.04):
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <grp.h>
int main(int argc, char *argv[])
{
printf("Here are all of this system's groups:\n\n");
struct group* grp;
while ((grp = getgrent()) != NULL)
puts(grp->gr_name);
endgrent();
exit(EXIT_SUCCESS);
}
I run the program with sudo and I get:
$ sudo ./program
Here are all of this system's groups:
Segmentation fault
Same error happens when working with struct spwd.
Update
I updated the source with the include lines and I left out the lib/*.c part. When I compile this exact piece of code:
$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/9/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none:hsa
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: [...]
Thread model: posix
gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)
$ gcc -std=c17 main.c -o program
main.c: In function ‘main’:
main.c:11:18: warning: implicit declaration of function ‘getgrent’ [-Wimplicit-function-declaration]
11 | while ((grp = getgrent()) != NULL)
| ^~~~~~~~
main.c:11:16: warning: assignment to ‘struct group *’ from ‘int’ makes pointer from integer without a cast [-Wint-conversion]
11 | while ((grp = getgrent()) != NULL)
| ^
main.c:14:4: warning: implicit declaration of function ‘endgrent’ [-Wimplicit-function-declaration]
14 | endgrent();
| ^~~~~~~~
And When I run it:
$ ./program
Here are all of this system's groups:
Segmentation fault (core dumped)
$ sudo ./program
Here are all of this system's groups:
Segmentation fault
Now when I run VS Code debugger it works correctly. VS Code is configured according to this article.
Here's my launch.json:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "gcc-9 - Build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "C/C++: gcc-9 build active file",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
Add the correct headers:
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <grp.h>
int main(int argc, char *argv[])
{
printf("Here are all of this system's groups:\n\n");
struct group* grp;
while ((grp = getgrent()) != NULL)
puts(grp->gr_name);
endgrent();
exit(EXIT_SUCCESS);
}
Update: -std=c17 is strange, it fails to include <grp.h> . You probably need std=gnu17, which includes some gnu+posix stuff.
I want to use C on Linux - VSCode. Therefore, I referred tutorial Using C++ on Linux in VS Code to use C/C++ extension, and accomplished to build hello world. Next, I want to test "include .h" by adding adder.h/.c:
//adder.h
#include <stdio.h>
int add(int a, int b);
//adder.c
#include "adder.h"
int add(int a, int b)
{
return a + b;
}
//main.c
#include <stdio.h>
#include "adder.h"
int main()
{
printf("ret = %d\n", add(1,2));
}
Those code can be build on DevC++ without any other setting. However, it showed error message after Terminal -> Run Build Task...
:
> Executing task: C/C++: gcc build active file <
Starting build...
/usr/bin/gcc -g /home/hughesyang/Test/c/projects/multi_files/main.c -o /home/hughesyang/Test/c/projects/multi_files/main
/tmp/ccvaDYKq.o: In function `main':
/home/hughesyang/Test/c/projects/multi_files/main.c:6: undefined reference to `add'
collect2: error: ld returned 1 exit status
Build finished with error(s).
The terminal process failed to launch (exit code: -1).
I'm not sure whether I need to modify DEFAULT tasks.json to solve that? Or it's caused by other mistake?
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: gcc build active file",
"command": "/usr/bin/gcc",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "compiler: /usr/bin/gcc"
}
]
}
PS. Using C++ on Linux in VS Code is a C++ example. Thus, I replace g++ with gcc as compiler for C.
Thanks for #WhozCraig's hint. It needs to use cmake to accomplish that. After referring Get started with CMake Tools on Linux and adding adder.c inside the add_executable() of CMakeLists.txt, it works!
cmake_minimum_required(VERSION 3.0.0)
project(helloworld_cmake VERSION 0.1.0)
include(CTest)
enable_testing()
add_executable(helloworld_cmake main.c adder.c)
set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)
I think it should be 6 hours I`m dealing with this problem! Anyway, I want to build a single .c file in vscode in linux ubuntu 64bit. Here is my code(quadratic-equation.c):
#include <stdio.h>
#include <math.h>
double quadratic_equation(float a, float b, float c);
int main()
{
float x, a, b, c;
printf("Enter a: ");
scanf("%f", &a);
printf("Enter b: ");
scanf("%f", &b);
printf("Enter c: ");
scanf("%f", &c);
x = quadratic_equation(a, b, c);
printf("form: ax%c + bx + c = 0:\n", 253);
printf("x = %f", x);
return 0;
}
double quadratic_equation(float a, float b, float c)
{
float x;
if(a == 0)
{
if(b == 0)
{
printf("a & b can not be both zero");
}
else
{
x = -c / b;
return x;
}
}
if((b * b - 4 * a * c ) == 0)
{
x = -b / (2 * a);
return x;
}
x = (-b + sqrt(b * b - 4 * a * c)) / 2 * a;
return x;
}
I have resolved all the problems in this code.
On the way to build, VSCode forced me to create 3 files, c_cpp_properties.json, launch.json, And tasks.json.
So, I copy paste them here:
My c_cpp_properties.json file:
{
"configurations": [
{
"name": "Linux",
"includePath": [
"/usr/include",
"/usr/local/include",
"${workspaceFolder}/**"
],
"defines": [
"_DEBUG",
"UNICODE"
],
"compilerPath": "/usr/bin/gcc",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "clang-x64",
"browse": {
"path": [
"${workspaceFolder}"
],
"limitSymbolsToIncludedHeaders": true,
"databaseFilename": ""
}
}
],
"version": 4
}
My launch.json file:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/quadratic-equation.c",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "build quadratic equation"
}
]
}
My tasks.json file:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "build quadratic equation",
"type": "shell",
"command": "g++",
"args": [
"-g", "quadratic-equation.c"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
And here is what gdb --version outputs:
GNU gdb (Ubuntu 8.1-0ubuntu3) 8.1.0.20180409-git
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word".
I also tried adding makefile file which didnt help.(I actually didnt know how to configure it, But I searched a little and had some tries, Which didn`t help).
And finally, Here is the error I get when I press f5 (start debugging):
Unable to start debugging. Program path '/home/amirali/XPSC/test/c-cpp/quadratic-equation.c' is missing or invalid.
GDB failed with message: "/home/amirali/XPSC/test/c-cpp/quadratic-equation.c": not in executable format: File format not recognized
This may occur if the process's executable was changed after the process was started, such as when installing an update. Try re-launching the application or restarting the machine.
Really thanks for your help
Finally found the answer.
Run gcc -g -o {executableDesiredFileName} {yourFile}.c -lm in the working folder and path "program" in launch.json to the executable file (-lm will try to include hadditional headers, and -o will rename the compiled program as the default is a.out).
I finally managed to configure the compiler for C in Sublime Text 2. In a int main() function, there is no problem with printf(), but there is a problem with the compiler using scanf(). It does not allow keyboard input and jump instruction.
There is the build code for C:
{
"cmd": ["gcc", "-Wall", "-ansi", "-pedantic-errors", "$file_name", "-o", "${file_base_name}.exe", "&&", "${file_base_name}.exe"],
"selector": "source.c",
"shell": true,
"working_dir": "$file_path"
}
There is the C code:
#include <stdio.h>
int main() {
int num, cube;
printf("Enter a number for know the cube: ");
scanf("%d", &num);
cube = num * num * num;
printf("\nThe cube %d is %d.\n\n", num, cube);
return 0;
}
Screenshot below:
error in scanf()
c build
You can't sent input to your program via the Sublime Text console. You can just see the output of build systems or commands ran by python.
The build system is intend to run programs such as compilers that do not need to interact with the user.
I recommend to remove the call to execute your .exe, meaning remove "&&", "${file_base_name}.exe" and run your program in the windows console. There it will work.
Though you can't fix sublime, you can adjust your C.sublime-build file to have it open a terminal window and run the program.
Here's my adjustment that launches a new terminal window so you can properly use sublime as a full IDE for simple C development.
{
"cmd": ["gcc", "${file}", "-o", "${file_path}/${file_base_name}"],
"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
"working_dir": "${file_path}",
"selector": "source.c",
"variants":
[
{
"name": "Run",
"cmd": ["bash", "-c", "gcc '${file}' -o '${file_path}/${file_base_name}' && open -a Terminal '${file_path}/${file_base_name}'"]
}
]
}
I'm sure there are better ways to launch the terminal window, but it works. If anyone has suggestions for improvements feel free to comment and I will adjust.