0

When trying to compile C code that includes math funcions like sqrt or pow terminal displays this error: Error Code in Terminal

This is the code:

#include <stdio.h>
#include <math.h>

void main()
{
int x1, y1, x2, y2, dx, dy;
float c;

printf("\nUpisite koordinate tacke A(x1 i y1): ");
scanf("%d%d", &x1, &y1);
printf("\nUpisite koordinate tacke B(x2 i y2): ");
scanf("%d%d", &x2, &y2);

dx = x2 - x1;
dy = y2 - y1;
c = sqrt((dx*dx) + (dy*dy));

printf("\nDve tace su udaljene %2.f", c);

return;
}

My classmate suggested that is is an error with linux and that I should add -lm at the end of terminal but I am trying to make this work in VSCode.

Vukašin
  • 17
  • 8
  • Did you review [this post](https://stackoverflow.com/questions/30269449/how-do-i-set-up-visual-studio-code-to-compile-c-code)? – Sercan Dec 16 '21 at 17:11

2 Answers2

1

To fix this issue, you can edit the Code-runner: Executor Map file, and add "-lm" in "c": "cd $dir && gcc $fileName -o $fileNameWithoutExt -lm && $dir$fileNameWithoutExt".

{
"workbench.colorTheme": "Default Dark+",
"code-runner.saveAllFilesBeforeRun": true,
"code-runner.saveFileBeforeRun": true,
"explorer.confirmDragAndDrop": false,
"code-runner.enableAppInsights": false,
"code-runner.showExecutionMessage": false,
"code-runner.clearPreviousOutput": true,
"code-runner.customCommand": "-lm",
"code-runner.defaultLanguage": "C",
"clangd.arguments": [
    "-lm"
],
"clangd.checkUpdates": true,
"workbench.editor.enablePreview": false,
"code-runner.runInTerminal": true,

"code-runner.executorMap": {
    "javascript": "node",
    "php": "C:\\php\\php.exe",
    "python": "python",
    "perl": "perl",
    "ruby": "C:\\Ruby23-x64\\bin\\ruby.exe",
    "go": "go run",
    "html": "\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe\"",
    "java": "cd $dir && javac $fileName && java $fileNameWithoutExt",
    "c": "cd $dir && gcc $fileName -o $fileNameWithoutExt -lm && $dir$fileNameWithoutExt"
}

}

CerfMetal
  • 66
  • 1
  • 2
0

VS Code does not automatically look for which header files you are using in your programm and link / include it.

You can see this through the command which VS Code runner runs i.e.

 cd {folder where the program is }
g++ {program.cpp}  
./{execute the binary}

you can see on the compilation stage that no extra libraries are linked or headers are included. You have to do that by yourself.

i.e. for your program

gcc z14.c -o z14 -lm

I also suggest learning a build automation tool like CMake which will make the task of compiling and linking very fluent.

Akki
  • 96
  • 1
  • 7