c++ - 使用 ubuntu 终端在 c++ 上运行线程类的问题

标签 c++ multithreading ubuntu lambda terminal

这个问题在这里已经有了答案:





What is an undefined reference/unresolved external symbol error and how do I fix it?

(38 个回答)


1年前关闭。




我决定在 C++ 中进行一些线程研究。
一切都很棒,Visual Studio 轻松编译它。
但是当我决定使用适用于 Windows 的 Ubuntu 终端来编译所有这些东西时——我在下面遇到了错误。
我试图编译如下:

  • g++ -o 线程 ThreadTest.cpp
  • g++ --std=c++17 -o 线程 ThreadTest.cpp

  • 已经尝试使用#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/

    相关文章:

    ubuntu - k8 在 bazel info local_cpu_resources 的输出中意味着什么

    c++ - 调用子类方法。指针与非指针

    c++ - 如何绑定(bind) C++ 公共(public)变量以在 lua 脚本中访问

    c# - 当您在 C# 任务等待程序上调用 `OnCompleted()` 时,您如何等待 OnCompleted 调用中给出的新作业?

    multithreading - 如果在同一进程中杀死线程A,线程B会发生什么?

    ubuntu - 如何在 ubuntu 16.04 上更改屏幕亮度

    php - 将 apache2 的默认 PHP 版本设置为特定版本

    c++ - C++ 中的 PID Controller 和传递函数

    c++ - 按升序对链表进行排序

    multithreading - 无需等待即可在线程之间发送消息