Unable to debug a single .c file in vscode - c

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).

Related

How to fix C header #include errors in VSCode on Mac?

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!

Linux getgrent() results in "Segmentation fault"

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.

Cannot build while I include own header file

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)

VSC C Include errors detected

I keep getting the errors #include errors detected. Please update your includePath. IntelliSense features for this translation unit (C:\Users\USERNAME\Documents\GIT\CS-262-004\HelloWorld.c) will be provided by the Tag Parser.C/C++(1696) and cannot open source file "stdio.h"
from the include statement I have tried Reinstalling the GCC from MINGW and I have added the file to the Path, I am using VSC so i added the C/C++ extension by microsoft and Code Runner by Jun han.
edit: added a semicolon after the printf statement and errors weren't fixed
My Code:
FileName - HelloWorld.c
#include <stdio.h>
int main() {
// printf() displays the string inside quotation
printf("Hello, World!");
return 0;
}
.vscode files
c_cpp_proporties.json
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"intelliSenseMode": "gcc-x64",
"compilerPath": "C:/MinGW/bin/gcc.exe"
}
],
"version": 4
settings.json
{
"files.associations": {
"HelloWorld.c": "c"
}
}

Visual Studio Code: arguments not passed to C command line application

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"

Resources