I am having trouble linking my libraries to the main file in vscode. I've made a simple example:
main.cpp
#include "io.h"
int main()
{
int x{read_number()};
int y{read_number()};
write_number(x + y);
return 0;
}
io.h
#ifndef IO_H
#define IO_H
int read_number();
void write_number(int number);
#endif
io.cpp
#include "io.h"
#include <iostream>
int read_number()
{
int x{};
std::cout << "Enter an integer: ";
std::cin >> x;
return x;
}
void write_number(int number)
{
std::cout << "The answer is " << number << '\n';
}
Attempting to build this with g++ and these settings
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "C/C++: g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-g",
"${file}",
"-I",
"${workspaceFolder}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": [
"$gcc"
],
"group": "build"
}
]
}
results in
> Executing task: /usr/bin/g++ -g /home/morten/learn_cpp/chp2/main.cpp -I /home/morten/learn_cpp/chp2 -o /home/morten/learn_cpp/chp2/main <
/tmp/cca6uKjD.o: In function 'main':
/home/morten/learn_cpp/chp2/main.cpp:5: undefined reference to 'read_number()'
/home/morten/learn_cpp/chp2/main.cpp:6: undefined reference to 'read_number()'
/home/morten/learn_cpp/chp2/main.cpp:8: undefined reference to 'write_number(int)'
collect2: error: ld returned 1 exit status
The terminal process terminated with exit code: 1
I am used to using cmake instead so I am not quite sure how to do this with vscode. I have looked online and been recommended to pass the library path using the -I
or -L
flags to g++ but it doesn't seem to help anything.