【问题标题】:c++ compile std::thread example with sconsc++ 用 scons 编译 std::thread 示例
【发布时间】:2012-10-15 18:12:21
【问题描述】:

我无法让 scons 正确编译一个小型线程示例(在 Linux 上)。

如果我运行 scons,它会这样做:

jarrett@jarrett-laptop:~/projects/c++_threads$ scons
scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
g++ -o build/main.o -c -std=c++11 -pthread -Wall -g src/main.cpp
g++ -o build/c++threads build/main.o
scons: done building targets.

如果我运行./build/c++threads,它会抛出这个错误:

terminate called after throwing an instance of 'std::system_error'
  what():  Operation not permitted
Aborted

如果我用这个从命令行编译:

g++ -std=c++11 -pthread -Wall -g src/main.cpp

它编译为a.out,如果我运行a.out,它会运行程序(为线程做一些输出等)。

这是我的 SConstruct 文件:

# Tell SCons to create our build files in the 'build' directory
VariantDir('build', 'src', duplicate=0)

# Set our source files
source_files = Glob('build/*.cpp', 'build/*.h')

# Set our required libraries
libraries = []
library_paths = ''

env = Environment()

# Set our g++ compiler flags
env.Append( CPPFLAGS=['-std=c++11', '-pthread', '-Wall', '-g'] )

# Tell SCons the program to build
env.Program('build/c++threads', source_files, LIBS = libraries, LIBPATH = library_paths)

这是 cpp 文件:

#include <iostream>
#include <thread>
#include <vector>

//This function will be called from a thread

void func(int tid) {
    std::cout << "Launched by thread " << tid << std::endl;
}

int main() {
    std::vector<std::thread> th;

    int nr_threads = 10;

    //Launch a group of threads
    for (int i = 0; i < nr_threads; ++i) {
        th.push_back(std::thread(func,i));
    }

    //Join the threads with the main thread
    for(auto &t : th){
        t.join();
    }

    return 0;
}

谁知道我做错了什么???

感谢任何帮助!

干杯

贾勒特

【问题讨论】:

  • 你不需要在链接器标志中添加-pthread吗?
  • @JoachimPileborg 如果链接和编译分两步完成,是的。

标签: c++ g++ pthreads scons


【解决方案1】:

感谢 @Joachim 和 @bamboon 的 cmets。将 pthread 添加到链接器(scons 库)标志有效。

新的 scons 文件现在是:

# Tell SCons to create our build files in the 'build' directory
VariantDir('build', 'src', duplicate=0)

# Set our source files
source_files = Glob('build/*.cpp', 'build/*.h')

# Set our required libraries
libraries = ['pthread']
library_paths = ''

env = Environment()

# Set our g++ compiler flags
env.Append( CPPFLAGS=['-std=c++11', '-pthread', '-Wall', '-g'] )

# Tell SCons the program to build
env.Program('build/c++threads', source_files, LIBS = libraries, LIBPATH = library_paths)

再次感谢!

【讨论】:

  • 注意:您也可以接受自己的答案,以表明它解决了问题。
  • 显然,我必须等待 2 天才能接受我自己的答案:\
猜你喜欢
  • 2013-11-26
  • 2021-08-03
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多