-2

I am learning C++ using Bjarne's book, everything was fine until I get to learn how to include header files.

My codes are as below:

my.h

#ifndef MY_H
#define MY_H

extern int foo;
void print_foo();

#endif

my.cpp

#include "my.h"
#include <iostream>

using namespace std;

void print_foo() {
    cout << foo << endl;
}

use.cpp

#include "my.h" 

int foo = 7;

int main() {
    print_foo();
}

I put them under the same folder with no space in folder name, I opened a new window from VS code, then I ran user.cpp and get the error saying undefined reference to print_foo.

Did I miss some key steps using VS code? because I think the codes are correct.

n33
  • 383
  • 4
  • 13
  • I haven't received any error after code build. Code is building and running fine. You need to build whole project and not single user.cpp file. – Sumeet May 06 '19 at 05:27
  • Looks good to me. Make certain that my.cpp is being compiled by putting in some garbage that can't possibly compile, like a line of aaaaaaaaaaaaaaaaaaaa, and seeing if you get an error message about the aaaaaaaaaaaaaaaaaaas. – user4581301 May 06 '19 at 05:29
  • you should build **both** cpps not only one. add to a project and build the project. – SHR May 06 '19 at 05:30
  • may I ask how to build a project in VS code, some source online says open a new window is equivalent – n33 May 06 '19 at 05:39
  • never mind, I fixed it by installing an extension – n33 May 06 '19 at 06:09

1 Answers1

2
g++ my.cpp use.cpp -o main

use this in the terminal

user4581301
  • 33,082
  • 7
  • 33
  • 54
rencedm112
  • 397
  • 3
  • 11