简体   繁体   English

链接头文件c ++时对函数的未定义引用

[英]Undefined reference to functions when linking header file c++

I'm trying to do the Chapter8's drill on the books of Bjarne stroustrup.我正在尝试在 Bjarne stroustrup 的书中进行第 8 章的练习。 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)'.我已按照所有步骤操作,但在运行程序时出现两个错误:未定义对“print_foo”的引用未定义对“print(int)”的引用。 I use VSC.我使用 VSC。

Here are my files:这是我的文件:

-----my.h----- ------我的.h-----

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

-------my.cpp-------- --------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-------- --------使用.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;
}

TL;DR: TL;博士:

compile the files use.cpp and my.cpp using g++ and declare foo outside main.使用 g++ 编译文件use.cppmy.cpp并在 main 之外声明foo


I was in this same exercise and had the same problem.我在同样的练习中遇到了同样的问题。

So here is my solution:所以这是我的解决方案:

Generally the extensions in vscode use one single file, so you will need to use the terminal to specify the other files (in this case, my.cpp).通常 vscode 中的扩展使用一个文件,因此您需要使用终端指定其他文件(在本例中为 my.cpp)。

my.h我的.h

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

my.cpp我的.cpp

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

void print_foo()
{
    cout << foo << endl; // foo is defined in use.cpp
}

void print(int i)
{
    cout << i << endl;
}

use.cpp使用.cpp

#include "my.h"

int foo; // foo is declared outside main. Foo is a global var
int main()
{
    foo = 7; //definition of foo
    print_foo();

    print(99);
}

Note that foo is defined outside main because my.h calls extern int foo;请注意, foo是在 main 之外定义的,因为my.h调用extern int foo; . .

Then, compile it using:然后,使用以下命令编译它:

g++ use.cpp my.cpp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM