1

I'm trying to do the Chapter8's drill on the books of Bjarne stroustrup. I have followed all the steps but when running the programme i get two errors: undefined reference to 'print_foo' undefined reference to 'print(int)'. I use VSC.

Here are my files:

-----my.h-----

extern int foo;
void print_foo();
void print(int);

-------my.cpp--------

#include"std_lib_facilities.h"
#include"my.h"

void print_foo() 
{
    cout<<"foo = "<<foo<<'\n';
}

void print(int i)
{
    cout<<"i = "<<i<<'\n';
}

-------use.cpp--------

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

using namespace std;

inline void keep_window_open() {char cc;cin>>cc;}

int main()
{   
    int foo = 7;
    print_foo();
    print(99);

    return 0;
}
  • Show the command line you used for linking, and/or whatever build settings you specified in your IDE. You probably aren't including `my.cpp` in the link. – Nate Eldredge Sep 18 '21 at 19:53
  • I'm using VSC. I just type Ctrl+Alt+N to execute the code. – MurDoc HoøBs Sep 18 '21 at 19:56
  • 3
    By default Visual Studio Code only builds one single source file, you need to build with both. Not knowing which OS you're using, I point you to [this VSCode with MinGW on Windows guide](https://code.visualstudio.com/docs/cpp/config-mingw), which very importantly also includes information about the configuration files used to build and which you can edit to build all source files. – Some programmer dude Sep 18 '21 at 19:58
  • I don't use VSCode so I'm not sure, but take a look at https://stackoverflow.com/questions/47665886/vs-code-will-not-build-c-programs-with-multiple-ccp-source-files which may help. – Nate Eldredge Sep 18 '21 at 19:58
  • However listing all the source files in the VSCode configuration file isn't going to work for larger projects, where one typically want things like dependency tracking and not rebuilding the whole project each build. For that look at something like [this VSCode and CMake guide](https://computingonplains.wordpress.com/building-c-applications-with-cmake-and-visual-studio-code/). There are also many more tools similar to CMake, it just happens to be a popular one. Do some research and find one you like. – Some programmer dude Sep 18 '21 at 20:01
  • Does the `int foo = 7;` as a local variable in `main` actually work as a definition for the `extern int foo;` declared in `my.h`? – Nathan Pierson Sep 18 '21 at 20:04
  • @NathanPierson No it does not. – Some programmer dude Sep 18 '21 at 20:10

0 Answers0