gpt4 book ai didi

c++ - 在多个文件中使用时包含全局 vector 时出错

转载 作者:太空宇宙 更新时间:2023-11-04 11:56:05 24 4
gpt4 key购买 nike

// Main.cpp
#include <iostream>
#include "common.h"
#include "second.cpp"
#include <vector>

int main(){
global = 10;
ip.push_back("TestTest");
std::cout << global << std::endl;
TestClass t;
t.print();
}

//common.h
#ifndef GLOBAL_H
#define GLOBAL_H
#include <vector>
#include <string>
extern int global;
extern std::vector<std::string> ip ;
#endif

// second.cpp

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

int global;

class TestClass{

public:
void print();};
void TestClass::print(){
global++;
std::cout << "Global: "<<global << std::endl;
std::cout << "IP String: "<<ip[0] << std::endl;
}

// Console Error
ubuntu:deleteme$ g++ main.cpp
/tmp/ccoJpYRl.o: In function `TestClass::print()':
main.cpp:(.text+0x55): undefined reference to `ip'
/tmp/ccoJpYRl.o: In function `main':
main.cpp:(.text+0xdd): undefined reference to `ip'
collect2: error: ld returned 1 exit status

当我只使用 int global 变量时,上面的代码有效。但是,当我将 vector ip 添加到 common.h 时,我收到了显示的错误。

这似乎是一个基本的东西,但无法得到答案。

提前致谢:)

最佳答案

您没有定义 std::vector<std::string> .使用 extern 你只需声明它是全局的但在另一个地方定义。您应该在 int global 下添加定义在second.cpp

// second.cpp

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

int global;
std::vector<std::string> ip;

class TestClass{

顺便说一句,你不应该使用全局变量。

关于c++ - 在多个文件中使用时包含全局 vector 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16074806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com