Include Mutex when building with G++ via Command Prompt?

I want to compile a C++ program that includes & uses the mutex library, with G++ via the Command Prompt on a Windows system. I'm attempting to compile with C++ 17.

My version of G++ is g++ (MinGW.org GCC-6.3.0-1) 6.3.0.

I'm normally able to compile simple programs via the g++ command on any Command Prompt. However, attempting to compile the following example file test.cpp:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <mutex>

std::mutex mut;

int main()
{
    std::cout << "test\n";
    
    return 0;
}


With the following command:

 
g++ -std=c++17 test.cpp -o test


Results in:

1
2
3
test.cpp:4:6: error: 'mutex' in namespace 'std' does not name a type
 std::mutex mut;
      ^~~~~


My understanding of this is what I need to supply a flag for the linker to link the library when issuing a build command with G++, however I'm not quite sure what that flag is for mutex and where to place it in the build command.

What is the linker flag required to supply to G++ to compile a C++ file that includes mutex?

Thanks for reading my post, any guidance is appreciated.
GCC-6.3 dates back to 2016
https://gcc.gnu.org/gcc-6/
Whilst it obviously supports some of C++17, it looks like support wasn't complete in that version.

Although having said that, std::mutex is from C++11, so I dunno.
https://en.cppreference.com/w/cpp/thread/mutex
Maybe it's just borked.


With a later compiler, there is no problem.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$ g++ --version
g++ (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0

$ cat foo.cpp
#include <iostream>
#include <mutex>

std::mutex mut;

int main()
{
    std::cout << "test\n";
    
    return 0;
}
$ g++ foo.cpp
$ ./a.out 
test
$ 


> What is the linker flag required to supply to G++ to compile a C++ file that includes mutex?
It's not a linker error, it's a compiler error.

Usually, there is no need to provide additional linker flags when pulling in code from the std:: namespace.
Last edited on
Looking to compile on a Windows system there are several newer options available for use. The current GCC release is 13.2, as others have said 6.3 is ancient.

MinGW-w64 is an update to the original MinGW project that provides support for x64 CPUs and newer APIs. (Hint, it can still compile x86/32-bit apps just fine)

There's another port that I know of MinGW64 available, LLVM.

There a couple of compiler suites available that use MinGW64/LLVM:

https://www.mingw-w64.org/downloads/

I have MSYS2, for a command-line compile setup it is fairly stress free.

https://www.msys2.org/

For day-to-day usage I prefer the Visual Studio IDE, though. I am bashing around in MSYS2 occasionally, though.

With MSYS2 installing and keeping updated packages is not that hard. The MSYS2 package manager is a nice feature.
Topic archived. No new replies allowed.