首页 > 解决方案 > 在 VS 代码中使用全局变量时出现“未定义的引用”错误

问题描述

我正在使用 Bjarne 的书学习 C++,一切都很好,直到我学会了如何包含头文件。

我的代码如下:

我的.h

#ifndef MY_H
#define MY_H

extern int foo;
void print_foo();

#endif

我的.cpp

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

using namespace std;

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

使用.cpp

#include "my.h" 

int foo = 7;

int main() {
    print_foo();
}

我将它们放在同一个文件夹下,文件夹名称中没有空格,我从 VS 代码打开了一个新窗口,然后我运行 user.cpp 并收到错误说未定义对 print_foo 的引用。

我是否错过了一些使用 VS 代码的关键步骤?因为我认为代码是正确的。

标签: c++visual-studio-code

解决方案


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

在终端中使用它


推荐阅读