这个问题在这里已经有了答案:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(38 个回答)
1年前关闭。
我决定在 C++ 中进行一些线程研究。
一切都很棒,Visual Studio 轻松编译它。
但是当我决定使用适用于 Windows 的 Ubuntu 终端来编译所有这些东西时——我在下面遇到了错误。
我试图编译如下:
已经尝试使用
#include <pthread.h>
,但在 Visual Studio 中找不到。我也在使用 lambda,我的代码中包含所有内容:
#include <chrono>
#include <functional>
#include <iostream>
#include <thread>
#include <vector>
这就是我在尝试用 Ubuntu 编译它时所采用的:In function `std::thread::thread<main::{lambda()#1}>(main::{lambda()#1}&&)':
ThreadTest.cpp:(.text+0x8b7): undefined reference to `pthread_create'
/tmp/cc0NzGGt.o: In function `std::thread::thread<void (&)(std::vector<int, std::allocator<int> >, std::vector<std::function<void (int)>, std::allocator<std::function<void (int)> > >), std::vector<int, std::allocator<int> >&, std::vector<std::function<void (int)>, std::allocator<std::function<void (int)> > >&>(void (&)(std::vector<int, std::allocator<int> >, std::vector<std::function<void (int)>, std::allocator<std::function<void (int)> > >), std::vector<int, std::allocator<int> >&, std::vector<std::function<void (int)>, std::allocator<std::function<void (int)> > >&)':
ThreadTest.cpp:(.text._ZNSt6threadC2IRFvSt6vectorIiSaIiEES1_ISt8functionIFviEESaIS6_EEEJRS3_RS8_EEEOT_DpOT0_[_ZNSt6threadC5IRFvSt6vectorIiSaIiEES1_ISt8functionIFviEESaIS6_EEEJRS3_RS8_EEEOT_DpOT0_]+0x39): undefined reference to `pthread_create'
/tmp/cc0NzGGt.o: In function `std::thread::thread<int (&)(int, int), std::reference_wrapper<int>, std::reference_wrapper<int> >(int (&)(int, int), std::reference_wrapper<int>&&, std::reference_wrapper<int>&&)':
ThreadTest.cpp:(.text._ZNSt6threadC2IRFiiiEJSt17reference_wrapperIiES4_EEEOT_DpOT0_[_ZNSt6threadC5IRFiiiEJSt17reference_wrapperIiES4_EEEOT_DpOT0_]+0x39): undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
最佳答案
为了使用线程,您必须确保链接正确的库。为此,只需添加 -lpthread
如:g++ -o thread ThreadTest.cpp -lpthread
关于c++ - 使用 ubuntu 终端在 c++ 上运行线程类的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62603396/