C++ 编译 std::线程示例与 scons.

c++ compile std::thread example with scons

本文关键字:scons 线程 编译 std C++      更新时间:2023-10-16

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

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

感谢任何帮助!

干杯

加里特

感谢@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)

再次感谢!