C++ 在多个文件中使用时包含全局向量时出错 //Main.cpp #包括 #包括“common.h” #包括“second.cpp” #包括 int main(){ 全局=10; ip.推回(“测试”); std::cout

C++ 在多个文件中使用时包含全局向量时出错 //Main.cpp #包括 #包括“common.h” #包括“second.cpp” #包括 int main(){ 全局=10; ip.推回(“测试”); std::cout,c++,C++,您没有定义std::vector。 使用extern,您只需声明它是全局的,但定义在另一个地方。 您应该在second.cpp中的int-global下添加定义 // Main.cpp #include <iostream> #include "common.h" #include "second.cpp" #include <vector> int main(){ global = 10; ip.push_back("TestTest"); std::co

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

// 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
//second.cpp
#包括
#包括“common.h”
int全球;
std::向量ip;
类TestClass{

另外,您不应该使用全局变量。

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

// 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
//second.cpp
#包括
#包括“common.h”
int全球;
std::向量ip;
类TestClass{

顺便说一句,你不应该使用globals。

ah!!愚蠢。谢谢。我喜欢Stackoverflow!在不到5分钟内得到答案。ah!!愚蠢。谢谢。我喜欢Stackoverflow!在不到5分钟内得到答案。