c++ - 在 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 代码的关键步骤?因为我认为代码是正确的。
解决方案
g++ my.cpp use.cpp -o main
在终端中使用它
推荐阅读
- yii2-advanced-app - 需要检查是否存在会话 yii2
- c# - 保存 https 页面,以便您可以证明来源
- node.js - 无法在 Windows 中为 React Native 安装 Expo
- uwp - 检测同时的鼠标右键和左键点击
- java - 我试图用这种方法来正确打印温度,但我卡住了
- r - R:按字母数字列对数据框中的所有列进行排序
- python - Sklearn.decomposition.PCA:按给定比例获取组件
- php - 有没有办法进行 wordpress 搜索查询,只需搜索具有自定义模板的页面?
- javascript - 使用 ajax 从另一个页面加载 html 时未定义函数
- batch-file - 批量获取存储在变量中的变量的值