0

I've started learning C++ and trying to figure out how header files work. I have main.cpp

#include <iostream>
#include "fibonacci.h"
using std::cout;
using std::cin;
using std::endl;

int main(){
   int n;
   cin >> n;
   for(int i = 0; i < n; i++)
       cout << fibonacci(i) << ", ";
   cout << endl;

   return 0;
}


fibonacci.h

#pragma once
int fibonacci(int n);

fibonacci.cpp

#include "fibonacci.h"

int fibonacci(int n){
    if(n == 0){
        return 0;
    }
    if(n == 1){
        return 1;
    }
    return fibonacci(n - 1) + fibonacci(n-2);
}

But while building I get undefined reference to 'fibonacci(int)' error.

I'm using VSCode and g++ compiler.

KindFrog
  • 358
  • 4
  • 17
  • 1
    Did you modify your `tasks.json` to build both files? The default configuration only builds the active file. The instructions how to build using more than 1 source file are here: [https://code.visualstudio.com/docs/cpp/config-mingw#_modifying-tasksjson](https://code.visualstudio.com/docs/cpp/config-mingw#_modifying-tasksjson) – drescherjm Sep 05 '20 at 13:25
  • 1
    That's indeed not a C++ problem but rather a problem with your VSCode configuration. You should be able to compile it fine manually, e.g. via `g++ main.cpp fibonacci.cpp -o main` – dtell Sep 05 '20 at 13:26

0 Answers0