c ++使用scons编译std :: thread示例

时间:2012-10-15 18:12:22

标签: c++ g++ pthreads scons

我无法让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;
}

任何人都知道我做错了什么???

感谢任何帮助!

干杯

Jarrett的

1 个答案:

答案 0 :(得分:5)

感谢@Joachim和@bamboon的评论。将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)

再次感谢!