2012-10-15 88 views
6

我无法让scons正确编译一个小的线程示例(在Linux上)。C++使用scons编译std :: thread示例

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

[email protected]:~/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它ru ns程序(为线程等做一些输出)。

这是我的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; 
} 

任何人有任何想法,我做错了???

感谢任何帮助!

干杯

贾勒特

+3

难道你不需要在链接器标志中添加'-pthread'吗? –

+1

@JoachimPileborg如果链接和编译分两步完成,是的。 – inf

回答

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) 

再次感谢!

+0

注意:您也可以接受自己的答案,以表明它解决了问题。 – inf

+0

显然,我必须等两天才能接受我自己的答案:\ – Jarrett