I am trying to use headers in vscode but I run through a lot of problems
this is print.c
#include <stdio.h>
void print1to10()
{
for (int i = 1; i <= 10; i++)
printf("%d ", i);
}
this is print.h
#ifndef PRINT_TO_10_H
#define PRINT_TO_10_H
#include <stdio.h>
void print1to10();
#endif
this is the main file main.c
#include <stdio.h>
#include "print.h"
int main()
{
print1to10();
return 0;
}
Just a simple program but it seems that vscode doesn’t like it
and it gives me this error
K:/test/main.c:6: undefined reference to 'print1to10' collect2.exe: error: ld returned 1 exit status
one more thing
I don’t know if it is relevant or not but I have played a little bit with C/C++ Configurations
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"windowsSdkVersion": "10.0.22000.0",
"compilerPath": "C:/msys64/mingw64/bin/gcc.exe",
"cStandard": "c99",
"cppStandard": "c++17",
"intelliSenseMode": "windows-gcc-x64"
}
],
"version": 4
}
I tried putting the print.c & print.h files in another folder in the same folder but then it gives me another error that it cannot even find the header file
K:testmain.c:2:10: fatal error: print.h: No such file or directory
2 | #include "print.h"
| ^~~~~~~~~
compilation terminated.
2
Answers
If you have a multiple files of multiple folders, for example with the following structure:
you can pass something like this to GCC.
And it would compile.
Alternatively you can try my VSCode extension that takes care of all the build configurations, running, debugging etc and also helps you create new, multi-library projects.
It’s called C Toolkit
The issue that you are having is that the file print.c is not linked to the executable. That’s why the function print1to10 is undefined.
When I run your main.c with the extension C/C++ it generates the following file in the folder .vscode
tasks.json
With this you can add the file print.c in the args section, so it’d look like this:
This will basically do the following command:
For more information you can check the documentation.
Additionally I modified a bit your code to remove redundace, however what you have should compile correctly.
print.h
print.c
main.c
Note: I have every file in the same folder, if you want to organise them in multiple folders, Usman Mehwood‘s answer is very accurate!