The issue is somewhat similar to this question but the accepted answer does not really propose a solution or workaround.
In our project, we have a dylib and the main executalble. The dylib is compiled with -fno-rtti, while the executable does use RTTI. The problem happens when an exception (e.g. std::bad_alloc) is thrown from the dylib and is caught in the exe.
(Before you yell "exceptions need RTTI so you must have it on!", please note that the RTTI necessary for exceptions is always generated regardless of the -frtti or -fno-rtti setting. This is actually documented in the -fno-rtti flag description. The issue on OS X is that it's not generated in the same way)
After some investigation, the following was discovered:
In the dylib (-fno-rtti), there is a local copy of the exception's RTTI structures; in particular, the __ZTISt9bad_alloc symbol (typeinfo for std::bad_alloc).
The exe (-frtti) imports the typeinfo symbol from libstdc++.6.dylib and does not have a local copy
Since the exception handling code relies on comparing typeinfo pointers to determine exception match, the matching fails, and only the catch(...) succeeds.
So far I see the following options:
1) compile everything, or at least the files that throw and catch exceptions, with -frtti. This is doable but I don't like the idea of generating RTTI for everything even if we don't use it; and the list of files which work with exceptions is prone to get stale.
2) when linking the dylib, somehow make the linker throw away the weak exception definition from the object file and use the one from libstdc++.6.dylib. So far I was not successful.
3) ???
I made a small test illustrating the problem.
--- throw.cpp ---
#include <iostream>
#if defined(__GNUC__)
#define EXPORT __attribute__((visibility("default")))
#else
#define EXPORT __declspec(dllexport)
#endif
EXPORT void dothrow ()
{
std::cout << "before throw" << std::endl;
throw std::bad_alloc();
}
--- main.cpp ---
#include <stdio.h>
#include <iostream>
#if defined(__GNUC__)
#define IMPORT extern
#else
#define IMPORT __declspec(dllimport)
#endif
IMPORT void dothrow ();
int main (void) {
try {
std::cout << "trying lib->main exception" << std::endl;
dothrow ();
}
catch ( const std::bad_alloc& )
{
std::cout << "caught bad_alloc in main - good." << std::endl;
}
catch (...)
{
std::cout << "caught ... in main - bad!" << std::endl;
}
}
--- makefile ---
# for main exe
CFLAGS_RTTI=-m32 -frtti -fvisibility=hidden -fvisibility-inlines-hidden -shared-libgcc -funwind-tables
# for dylib
CFLAGS_NORTTI=-m32 -fno-rtti -fvisibility=hidden -fvisibility-inlines-hidden -shared-libgcc
# for linking; some switches which don't help
CLFLAGS=-Wl,-why_live,-warn_commons,-weak_reference_mismatches,error,-commons,error
all: test
test: libThrow.dylib main.o
g++ $(CFLAGS_RTTI) -o test main.o -lthrow -L./ $(CLFLAGS)
main.o: main.cpp
g++ $(CFLAGS_RTTI) -c -o main.o main.cpp
throw.o: throw.cpp
g++ $(CFLAGS_NORTTI) -c -o throw.o throw.cpp
libThrow.dylib: throw.o
g++ $(CFLAGS_NORTTI) -dynamiclib -o libThrow.dylib throw.o
clean:
rm test main.o throw.o
Running:
$ ./test
trying lib->main exception
before throw
caught ... in main - bad!
Symbols of the files involved:
$ nm -m throw.o | grep bad_alloc
000001be (__TEXT,__textcoal_nt) weak private external __ZNSt9bad_allocC1Ev
000001be (__TEXT,__textcoal_nt) weak private external __ZNSt9bad_allocC1Ev
00000300 (__TEXT,__eh_frame) weak private external __ZNSt9bad_allocC1Ev.eh
(undefined) external __ZNSt9bad_allocD1Ev
00000290 (__DATA,__const_coal) weak external __ZTISt9bad_alloc
000002a4 (__TEXT,__const_coal) weak external __ZTSSt9bad_alloc
(undefined) external __ZTVSt9bad_alloc
$ nm -m libThrow.dylib | grep bad_alloc
00000ce6 (__TEXT,__text) non-external __ZNSt9bad_allocC1Ev
(undefined) external __ZNSt9bad_allocD1Ev (from libstdc++)
00001050 (__DATA,__const) weak external __ZTISt9bad_alloc
00000e05 (__TEXT,__const) weak external __ZTSSt9bad_alloc
(undefined) external __ZTVSt9bad_alloc (from libstdc++)
$ nm -m main.o | grep bad_alloc
(undefined) external __ZTISt9bad_alloc
$ nm -m test | grep bad_alloc
(undefined) external __ZTISt9bad_alloc (from libstdc++)
Note: similar compilation options on Linux and Windows works fine. I can throw exceptions from a shared object/dll and catch them in the main exe, even if they're compiled with different -frtti/-fno-rtti options.
EDIT: here's how I ended up solving it for the specific case of bad_alloc:
#if defined(__GLIBCXX__) || defined(_LIBCPP_VERSION)
#define throw_nomem std::__throw_bad_alloc
#else
#define throw_nomem throw std::bad_alloc
#endif
EXPORT void dothrow ()
{
std::cout << "before throw" << std::endl;
throw_nomem();
}
The function __throw_bad_alloc is imported from libstdc++.6.dylib and so always throws a correct type.
You can simply move all your "throw exceptions" infrastructure to the helper library with -frtti enabled - and link it to other stuff. Without actual code it's hard to tell, if this decomposition is possible or not.
Here is some sample code:
// Thrower.cc
void DoThrow() {
throw std::bad_alloc;
}
// LibraryNoRTTI.cc
void f() {
DoThrow();
}
// main.cc
int main() {
try {
f();
}
catch(std::bad_alloc&) {}
return 0;
}
The simplest way is to move all your throw invocations to the separate functions with appropriate types, like: throw std::logical_error("message"); goes to void ThrowLogicError(const std::string& message) { ... }
If there is a problem with encapsulation (private exception classes), then you may make friends with throwing functions.
If you still want to use (throw/catch) exceptions inside the non-rtti library, then you have to make separation between internal exceptions and exceptions used in your library API.
The good way is to use native C++ throw-catch for internal purposes - and then rethrow some exceptions, using rtti-based library functions, to the outside - according to your interface:
// Thrower.cc
void Rethrow(const std::exception& e) {
throw e;
}
// LibraryNoRTTI.cc
namespace {
void internal_stuff() {
throw std::logical_error("something goes wrong!");
}
} // namespace
// You even may explicitly specify the thrown exceptions in declaration:
void f() throw(std::logical_error) {
try {
internal_stuff();
}
catch(std::exception& e) {
Rethrow(std::logical_error(std::string("Internal error: ") + e.what());
}
}
Start Edit March 4, 2014
I think the Clang++ compiler has a better chance of obtaining the desired exception handling. I have found this Stack Overflow post: Clang and the default compiler in OS X Lion. The post has helpful script lines for modifying ~/.bashrc to change the system default compiler settings on Snow Leopard and how to use the LLVM GCC. For Clang, add inside the ~/.bashrc:
# Set Clang as the default compiler for the system
export CC=clang
export CFLAGS=-Qunused-arguments
export CPPFLAGS=-Qunused-arguments
If the c++ symbolic link is not present, either call clang++ directly or add the c++ link as desired (e.g.
ln -s /usr/bin/clang++ c++
). It is a good idea to check all symbolic links within the /usr/bin by running:
ls -l `which lynx` | more
On my Mavericks command line tools installation c++ points to clang++ and cc points to clang. The g++ compiler version says:
$ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx- include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin13.0.0
Thread model: posix
The clang++ complier version says:
$clang++ --version
Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin13.0.0
Thread model: posix
Notice that the g++ include directory path is set to /usr/include/c++/4.2.1, probably not the include path needed to resolve the issue.
MacPorts: Hopefully the Answer for any OS X version
The best solution I can find to obtain any Clang++ compiler version for any OS X version is to use the open source tool called MacPorts. There is extensive documentation in the MacPorts Guide. The application is called port and can be installed from an OS X installation package or obtain the source code and compile locally. The following is from installing MacPorts onto Snow Leopard. The other OS X versions should be similar. After obtaining MacPorts for Snow Leopard, run the port search command to observe all the different clang related ports available. For example, it looks like this:
$port search clang
The partial list of search results from Snow Leopard 10.6.8 is:
clang-2.9 #2.9_13 (lang)
C, C++, Objective C and Objective C++ compiler
clang-3.0 #3.0_12 (lang)
C, C++, Objective C and Objective C++ compiler
clang-3.1 #3.1_7 (lang)
C, C++, Objective C and Objective C++ compiler
clang-3.2 #3.2_2 (lang)
C, C++, Objective C and Objective C++ compiler
clang-3.3 #3.3_2 (lang)
C, C++, Objective C and Objective C++ compiler
clang-3.4 #3.4 (lang)
C, C++, Objective C and Objective C++ compiler
clang-3.5 #3.5-r202097 (lang)
C, C++, Objective C and Objective C++ compiler
clang_select #0.1 (sysutils)
common files for selecting default clang version
Then I successfully installed clang-3.3 with: sudo port install clang-3.3. After this completes, see the available versions by typing port select --list clang. Then run the
sudo port select --set clang mp-clang-3.3
or similar. When I execute clang++ --version it says (as expected):
clang version 3.3 (tags/RELEASE_33/final)
Target: x86_64-apple-darwin10.8.0
Thread model: posix
Same for when the clang --version command is executed (after closing and restarting the terminal):
clang version 3.3 (tags/RELEASE_33/final)
Target: x86_64-apple-darwin10.8.0
Thread model: posix
There are MacPorts installation packages for many OS X versions (e.g. Leopard, Snow Leopard, Lion, Mountain Lion, Mavericks, etc.). I did not go any further back than Leopard with my search. If using an OS X older than Leopard, please review the MacPorts site thoroughly.
If curious about details on where to find Xcode 4.2 (or used to be able to obtain it), I have found this post regarding obtaining Xcode 4.2 for Snow Leopard Xcode 4.2 download for Snow Leopard. Then these two additional ones: Can i use the latest features of C++11 in XCode 4 or OSX Lion? [duplicate] and Can I use C++11 with Xcode?. After trying a couple links to see if the 4.2 Xcode remains available for Snow Leopard, no joy.
More than likely the MacPorts libc++ installation will be necessary to have full C++11 support. To install the more recent version, execute sudo port install libcxx. The contents of the /usr/lib will be overwritten with the current C++11 libraries (as necessary per MacPorts Ticket #42385: libcxx/libcxxabi: OS update can render system unusable
If libc++ still appears to be lacking, try this: "libc++" C++ Standard Library. Then use this:
$ export TRIPLE=-apple-
$ export MACOSX_DEPLOYMENT_TARGET=10.6
$ ./buildit
from How to build libc++ with LLVM/Clang 3.3 on Mac OS X 10.6 "Snow Leopard".
On OS X Lion, Mountain Lion, and Mavericks, they all have recent independent command line tools downloads on the Apple Developer site. The Clang version may be older than what one needs, so be sure to confirm which C++11 features are needed when using the Developer site command line tools' Clang.
End Edit March 4, 2014
The above macro detection may need to change from __GNUC__ to __clang__ or __clang_version__. It all depends on what the predefined compiler macros are for each OS X compiler, and the best way to detect as needed here. The Stack Overflow answer at: What predefined macro can I use to detect clang? should be helpful in configuring the command line to obtain them (e.g. clang++ -dM -E -x c /dev/null).
I have noticed when running the preceding example command that there is a predefined macro called __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__. On the Mavericks clang++, the macro value is 1090. It might be necessary to have a family of #ifdef logic to set the appropriate EXPORT macro for each OS X clang++ compiler.
Well, even though I have accepted an answer it did not solve all problems. So I'm writing down the solution which did work in the end.
I made a small tool for post-processing the object files and marking the local symbols as UNDEF. This forces the linker to use definitions from libstdc++ and not local ones from the file. The basic approach of the tool is:
load the Mach-O header
walk the load commands and find the LC_SYMTAB command
load the list of symbols (struct nlist) and the strings
walk the symbols and look for those that we need (e.g. __ZTISt9bad_alloc)
set the found symbols' type to N_UNDF|N_EXT.
after processing, write the modified symbol table back to the file.
(I also made a similar implementation for ELF)
I post-process any file that's using std exceptions, either for throwing or for catching. To make sure the file list does not go stale, I added a post-link check for unwanted local symbols using nm.
This seems to resolve all the problems I've had so far.
Related
I have a piece of code that looks like the following. Let's say it's in a file named example.cpp
#include <fstream>
#include <string> // line added after edit for clarity
int main() {
std::string filename = "input.txt";
std::ifstream in(filename);
return 0;
}
On a windows, if I type in the cmd the command g++ example.cpp, it will fail. It's a long list of errors I think mostly due to the linker complaining about not being able to convert from string to const char*.
But if I run the compiler using an additional argument like so: g++ -std=c++17 example.cpp, it will compile and work fine with no problems.
What happens when I run the former command? I'm guessing a default version standard of the C++ compiler gets called, but I don't know which? And as a programmer/developer, should I always use the latter command with the extra argument?
If your version of g++ is later than 4.7 I think you can find the default version of C++ standard supported like so:
g++ -dM -E -x c++ /dev/null | grep -F __cplusplus
An example from my machine:
mburr#mint17 ~ $ g++ --version | head -1
g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
mburr#mint17 ~ $ g++ -dM -E -x c++ /dev/null | grep -F __cplusplus
#define __cplusplus 199711L
Some references:
Details on the g++ options used
Why this only works for g++ 4.7 or later
g++ man page actually tells what is the default standard for C++ code.
Use following script to show the relevant part:
man g++ | col -b | grep -B 2 -e '-std=.* This is the default'
For example, in RHEL 6 g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-23), the output:
gnu++98
GNU dialect of -std=c++98. This is the default for C++ code.
And in Fedora 28 g++ (GCC) 8.1.1 20180502 (Red Hat 8.1.1-1), the output:
gnu++14
gnu++1y
GNU dialect of -std=c++14. This is the default for C++ code. The name gnu++1y is deprecated.
You can also check with gdb
$ g++ example.cpp -g Compile program with -g flag to generate debug info
$ gdb a.out Debug program with gdb
(gdb) b main Put a breakpoint at main
(gdb) run Run program (will pause at breakpoint)
(gdb) info source
Prints out something like:
Current source file is example.cpp
Compilation directory is /home/xxx/cpp
Located in /home/xxx/cpp/example.cpp
Contains 7 lines.
Source language is c++.
Producer is GNU C++14 6.3.0 20170516 -mtune=generic -march=x86-64 -g.
Compiled with DWARF 2 debugging format.
Does not include preprocessor macro info.
There is the standard used by compiler: Producer is GNU C++14
If you recompile your program using -std=c++11 (for example), gdb detects it:
Producer is GNU C++11
I believe that it is possible to tell by looking at the man page (at least for g++):
Under the description of -std, the man page lists all C++ standards, including the GNU dialects. Under one specific standard, it is rather inconspicuously stated, This is the default for C++ code. (there is an analogous statement for C standards: This is the default for C code.).
For instance, for g++/gcc version 5.4.0, this is listed under gnu++98/gnu++03, whereas for g++/gcc version 6.4.0, this is listed under gnu++14.
I'm guessing a default version of the C++ compiler gets called, but I don't know which?
This is only guessable by reading the documentation of your particular compiler version.
If using a recent GCC, I recommend first to understand what version are you using by running
g++ -v
or
g++ --version
and then refer to the version of the particular release of GCC. For example for GCC 7, read GCC 7 changes etc
Alternatively, run
g++ -dumpspecs
and decipher the default so called spec file.
BTW, you could ensure (e.g. in some of your common header file) that C++ is at least C++17 by coding
#if __cplusplus < 201412L
#error expecting C++17 standard
#endif
and I actually recommend doing it that way.
PS. Actually, think of C++98 & C++17 being two different languages (e.g. like Ocaml4 and C++11 are). Require your user to have a compiler supporting some defined language standard (e.g. C++11), not some particular version of GCC. Read also about package managers.
If you are using the GCC compiler, you can find it on the man pages:
man g++ | grep "This is the default for C++ code"
Typing g++ --version in your command shell will reveal the version of the compiler, and from that you can infer the default standard. So you can't tell directly but you can infer it, with some effort.
Compilers are supposed to #define __cplusplus which can be used to extract the standard that they purport to implement at compile time; but many don't do this yet.
(And don't forget to include all the C++ standard library headers you need: where is the one for std::string for example? Don't rely on your C++ standard library implementation including other headers automatically - in doing that you are not writing portable C++.)
Your question is specific to gnu compilers, so probably better to tag it appropriately, rather than just C++ and C++11.
Your code will compile with any compilers (and associated libraries) compliant with C++11 and later.
The reason is that C++11 introduced a std::ifstream constructor that accepts a const std::string &. Before C++11, a std::string could not be passed, and it would be necessary in your code to pass filename.c_str() rather than filename.
According to information from gnu, https://gcc.gnu.org/projects/cxx-status.html#cxx11, gcc.4.8.1 was the first version to fully support C++11. At the command line g++ -v will prod g++ to telling you its version number.
If you dig into documentation, you might be able to find the version/subversion that first supported enough features so your code - as given - would compile. But such a version would support some C++11 features and not others.
Since windows isn't distributed with g++, you will have whatever version someone (you?) has chosen to install. There will be no default version of g++ associated with your version of windows.
The default language standards for both C and C++ are specified in the GCC Manuals. You can find these as follows:
Browse to https://gcc.gnu.org/onlinedocs/
Select the GCC #.## Manual link for the version of GCC you are interested in, e.g. for GCC 7.5.0:
https://gcc.gnu.org/onlinedocs/gcc-7.5.0/gcc/
Click the topic link Language Standards Supported by GCC, followed by the topic C++ Language (or C language). Either of these topics will have a sentence such as:
The default, if no C++ language dialect options are given, is -std=gnu++14.
The default, if no C language dialect options are given, is -std=gnu11.
The above two examples are for GCC 7.5.0.
I have a piece of code that looks like the following. Let's say it's in a file named example.cpp
#include <fstream>
#include <string> // line added after edit for clarity
int main() {
std::string filename = "input.txt";
std::ifstream in(filename);
return 0;
}
On a windows, if I type in the cmd the command g++ example.cpp, it will fail. It's a long list of errors I think mostly due to the linker complaining about not being able to convert from string to const char*.
But if I run the compiler using an additional argument like so: g++ -std=c++17 example.cpp, it will compile and work fine with no problems.
What happens when I run the former command? I'm guessing a default version standard of the C++ compiler gets called, but I don't know which? And as a programmer/developer, should I always use the latter command with the extra argument?
If your version of g++ is later than 4.7 I think you can find the default version of C++ standard supported like so:
g++ -dM -E -x c++ /dev/null | grep -F __cplusplus
An example from my machine:
mburr#mint17 ~ $ g++ --version | head -1
g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
mburr#mint17 ~ $ g++ -dM -E -x c++ /dev/null | grep -F __cplusplus
#define __cplusplus 199711L
Some references:
Details on the g++ options used
Why this only works for g++ 4.7 or later
g++ man page actually tells what is the default standard for C++ code.
Use following script to show the relevant part:
man g++ | col -b | grep -B 2 -e '-std=.* This is the default'
For example, in RHEL 6 g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-23), the output:
gnu++98
GNU dialect of -std=c++98. This is the default for C++ code.
And in Fedora 28 g++ (GCC) 8.1.1 20180502 (Red Hat 8.1.1-1), the output:
gnu++14
gnu++1y
GNU dialect of -std=c++14. This is the default for C++ code. The name gnu++1y is deprecated.
You can also check with gdb
$ g++ example.cpp -g Compile program with -g flag to generate debug info
$ gdb a.out Debug program with gdb
(gdb) b main Put a breakpoint at main
(gdb) run Run program (will pause at breakpoint)
(gdb) info source
Prints out something like:
Current source file is example.cpp
Compilation directory is /home/xxx/cpp
Located in /home/xxx/cpp/example.cpp
Contains 7 lines.
Source language is c++.
Producer is GNU C++14 6.3.0 20170516 -mtune=generic -march=x86-64 -g.
Compiled with DWARF 2 debugging format.
Does not include preprocessor macro info.
There is the standard used by compiler: Producer is GNU C++14
If you recompile your program using -std=c++11 (for example), gdb detects it:
Producer is GNU C++11
I believe that it is possible to tell by looking at the man page (at least for g++):
Under the description of -std, the man page lists all C++ standards, including the GNU dialects. Under one specific standard, it is rather inconspicuously stated, This is the default for C++ code. (there is an analogous statement for C standards: This is the default for C code.).
For instance, for g++/gcc version 5.4.0, this is listed under gnu++98/gnu++03, whereas for g++/gcc version 6.4.0, this is listed under gnu++14.
I'm guessing a default version of the C++ compiler gets called, but I don't know which?
This is only guessable by reading the documentation of your particular compiler version.
If using a recent GCC, I recommend first to understand what version are you using by running
g++ -v
or
g++ --version
and then refer to the version of the particular release of GCC. For example for GCC 7, read GCC 7 changes etc
Alternatively, run
g++ -dumpspecs
and decipher the default so called spec file.
BTW, you could ensure (e.g. in some of your common header file) that C++ is at least C++17 by coding
#if __cplusplus < 201412L
#error expecting C++17 standard
#endif
and I actually recommend doing it that way.
PS. Actually, think of C++98 & C++17 being two different languages (e.g. like Ocaml4 and C++11 are). Require your user to have a compiler supporting some defined language standard (e.g. C++11), not some particular version of GCC. Read also about package managers.
If you are using the GCC compiler, you can find it on the man pages:
man g++ | grep "This is the default for C++ code"
Typing g++ --version in your command shell will reveal the version of the compiler, and from that you can infer the default standard. So you can't tell directly but you can infer it, with some effort.
Compilers are supposed to #define __cplusplus which can be used to extract the standard that they purport to implement at compile time; but many don't do this yet.
(And don't forget to include all the C++ standard library headers you need: where is the one for std::string for example? Don't rely on your C++ standard library implementation including other headers automatically - in doing that you are not writing portable C++.)
Your question is specific to gnu compilers, so probably better to tag it appropriately, rather than just C++ and C++11.
Your code will compile with any compilers (and associated libraries) compliant with C++11 and later.
The reason is that C++11 introduced a std::ifstream constructor that accepts a const std::string &. Before C++11, a std::string could not be passed, and it would be necessary in your code to pass filename.c_str() rather than filename.
According to information from gnu, https://gcc.gnu.org/projects/cxx-status.html#cxx11, gcc.4.8.1 was the first version to fully support C++11. At the command line g++ -v will prod g++ to telling you its version number.
If you dig into documentation, you might be able to find the version/subversion that first supported enough features so your code - as given - would compile. But such a version would support some C++11 features and not others.
Since windows isn't distributed with g++, you will have whatever version someone (you?) has chosen to install. There will be no default version of g++ associated with your version of windows.
The default language standards for both C and C++ are specified in the GCC Manuals. You can find these as follows:
Browse to https://gcc.gnu.org/onlinedocs/
Select the GCC #.## Manual link for the version of GCC you are interested in, e.g. for GCC 7.5.0:
https://gcc.gnu.org/onlinedocs/gcc-7.5.0/gcc/
Click the topic link Language Standards Supported by GCC, followed by the topic C++ Language (or C language). Either of these topics will have a sentence such as:
The default, if no C++ language dialect options are given, is -std=gnu++14.
The default, if no C language dialect options are given, is -std=gnu11.
The above two examples are for GCC 7.5.0.
--EDIT
If you would like to use MinGW GCC 8.4.1 and threads/mutex/futures/atomics do not download the Win32 threader version insted download the Posix version.
--EDIT
My installation of MinGW is as follows:
x32-4.8.1-release-win32 (as the threader) - sjlj rev 5
I have unpacked and correctly confirmed that MinGW GCC 4.8.1 (revision 5) is installed in C:\MinGW\mingw32. I have set up Code Blocks to look for the latest and greatest compiler in the correct path (this I am sure of). I can compile a normal program using #include iostream. Ok now when I try and run a program using #include thread it gives me "error: 'thread' is not a member of 'std'".
Now here is what I have done and what I have tried:
I am following a sort of template or tutorial here at cplusplus.com.
I have the code exactly as it is presented on the webpage (towards the bottom).
I have tried, in Code Blocks, to use Compiler flags "Have g++ follow the C++11 ISO language standard -std=c++11".
I have also tried the flag "Have g++ follow the coming C++0x ISO language standard -std=c++0x"
I have tried both at the same time and one at a time, no mas.
I have also tried those commands manually.
Another command I tried manually was -std=gnu++11 which was recommended in the thread header.
--EDIT
It seems like __cplusplus is < 201103L which is stated (or rather defined) in the thread header.
This only happens when I manually use -std=c++11, for some reason C::B removes it if it was manually stated so I must use a check box to use this flag...
--EDIT
My compiler settings under the Toolchain Executables tab are as follows:
C compiler: i686-w64-mingw32-gcc-4.8.1.exe
C++ compiler: i686-w64-mingw32-c++.exe
Linker for dynamic: i686-w64-mingw32-c++.exe
Linker for static: ar.exe
Debbuger: GDB/CDB debugger: default
Resource compiler: windres.exe
Make Program: mingw32-make.exe
I have tried using other executables in the bin folder and still no luck...
I'm starting to wonder if GCC supports C++11 or threading !?
Has anyone been able to get threads to work with MinGW GCC, Code blocks or in general?
If so how did you do it? Any links that might help? Any advice?
P.S. I know there are other ways of threading like posix or other SDK's like SFML (I have successfully tried threading with this). But I want to use GCC threading and I'm quite baffled as to why it is so hard to do seeing as all the necessary files are there...
--EDIT
I have found that when I manually compile the program outside of Code Blocks I still get the same errors, whether I use g++ c++ or i686-w64-mingw32-g++/c++
here is the command I run to build the files:
C:\MinGW\mingw32\bin>g++.exe -D__GXX_EXPERIMENTAL_CXX0X__ -o0 -g3
-Wall -c -fmes sage-length=0 -std=c++11 -Wc++11-compat -o obj\Debug\main.o "F:\C Projects\Code Blocks\thread\main.cpp"
still returns error: 'thread' is not a member of 'std'
Could this be a bad build? I will try other revisions...
--EDIT
probably to late for an answere, but here is what worked for me:
1. Get x86_64-w64-mingw32-gcc-4.8-stdthread-win64_rubenvb.7z from:
http://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win64/Personal%20Builds/rubenvb/gcc-4.8-experimental-stdthread/
2. Setup a new compiler in codeblocks with
x86_64-w64-mingw32-gcc-4.8.1.exe
x86_64-w64-mingw32-g++.exe
x86_64-w64-mingw32-g++.exe
ar.exe
windres.exe
mingw32-make.exe
3. Set the new compiler for your project
Right click in your project -> build options
Select the new compiler
Under compiler falgs check -std=c++0x and -std=c++11
Under Other options set -std=gnu++11
4. Have fun with c++11 concurrency
Hope that works for you also, as an alternative you can just use visual studio.
I think you meant GCC 4.8.1 - the answer is yes, it supports a set of C++11 features including partial multi-threading support. Please visit http://gcc.gnu.org/releases.html to see supported set.
gcc 4.8.1 is C++11 feature complete. I cannot speak to the Windows implementation but certainly on Linux and OS X it works as advertised, including all the concurrency functionality. I just #include <thread> and call g++ -std=gnu++11 and it works. Here's a minimal piece of code that compiles just fine:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mx;
int i;
void thrfunc();
int main(void)
{
i=0;
std::thread thr1(thrfunc),thr2(thrfunc);
thr1.join();
thr2.join();
return 0;
}
void thrfunc()
{
mx.lock();
i++;
std::cout << std::this_thread::get_id() << " i: " << i << std::endl;
mx.unlock();
}
I had the same issues, I installed the lates MinGW-Builds
http://sourceforge.net/projects/mingwbuilds/files/mingw-builds-install/
and set my toolchain executables to:
x86_64-w64-mingw32-gcc-4.8.1.exe
x86_64-w64-mingw32-g++.exe
x86_64-w64-mingw32-g++.exe
ar.exe
windres.exe
mingw32-make.exe
I hope this helps.
I'm writing a simple C++ program to demonstrate the use of locks. I am using codeblocks and gnu gcc compiler.
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
int x = 0; // shared variable
void synchronized_procedure()
{
static std::mutex m;
m.lock();
x = x + 1;
if (x < 5)
{
cout<<"hello";
}
m.unlock();
}
int main()
{
synchronized_procedure();
x=x+2;
cout<<"x is"<<x;
}
I'm getting the following error: mutex in namespace std does not name a type.
Why am I getting this error?
Doesn't the compiler support use of locks?
I happened to be looking at the same problem. GCC works fine with std::mutex under Linux. However, on Windows things seem to be worse. In the <mutex> header file shipped with MinGW GCC 4.7.2 (I believe you are using a MinGW GCC version too), I have found that the mutex class is defined under the following #if guard:
#if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1)
Regretfully, _GLIBCXX_HAS_GTHREADS is not defined on Windows. The runtime support is simply not there.
You may also want to ask questions directly on the MinGW mailing list, in case some GCC gurus may help you out.
EDIT: The MinGW-w64 projects provides the necessary runtime support. Check out http://mingw-w64.sourceforge.net/ and https://sourceforge.net/projects/mingw-w64/files/. Also, as 0xC0000022L pointed out, you need to download the POSIX thread version (I missed mentioning it last time).
Use POSIX threading model for MINGW:
$ sudo update-alternatives --config i686-w64-mingw32-gcc
<choose i686-w64-mingw32-gcc-posix from the list>
$ sudo update-alternatives --config i686-w64-mingw32-g++
<choose i686-w64-mingw32-g++-posix from the list>
$ sudo update-alternatives --config x86_64-w64-mingw32-gcc
<choose x86_64-w64-mingw32-gcc-posix from the list>
$ sudo update-alternatives --config x86_64-w64-mingw32-g++
<choose x86_64-w64-mingw32-g++-posix from the list>
See also: mingw-w64 threads: posix vs win32
This has now been included in MingW (Version 2013072300). To include it you have to select the pthreads package in the MinGW Installation Manager.
Mutex, at least, is not supported in 'Thread model: win32' of the Mingw-builds toolchains. You must select any of the toolchains with 'Thread model: posix'. After trying with several versions and revisions (both architectures i686 and x86_64) I only found support in x86_64-4.9.2-posix-seh-rt_v3-rev1 being the thread model, IMO, the determining factor.
I encountered this same problem when using MingW-W64 7.2.0. I tested out several different Windows builds from the mingw-64 download page, and found that MinGW-W64 GCC-8.1.0 supports mutex and contains the pthread library. When installing, I selected the following options:
x86_64
posix
seh
My multi-threaded code based on pthreads now compiles and runs cleanly on both Windows and Linux with no changes.
This version is leaner than the 7.3.0 build I was using because it doesn't have a CygWin environment or package manager. I also copied mingw32-make.exe to make.exe so my Makefile wouldn't need to be modified. The installer creates a "Run terminal" link in the Windows Start Menu.
I got the same error with gcc4.7.7.
After adding "-std=c++0x", it is fixed.
my gcc version is 5.4 and i solved this problem when adding #include and also adding -std=c++11 at my CmakeLists.txt as below:
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -O3 -march=native -std=c++11")
I fixed it by following steps:
Project > Build option...
The default selected compiler: GNU GCC Compiler
On tab "Compiler settings / Compiler flags", check option
"Have g++ follow the C++11 ISO C++ language standard [-std=c++11]"
I don't know if it works for everybody, but in other way you just have to update your ndk. I'm using ndk-r11c and it works perfectly.
Many classes of the standard thread library can be replaced with the boost ones. A very easy workaround is to change the entire standard mutex file with a couple of lines.
#include <boost/thread.hpp>
namespace std
{
using boost::mutex;
using boost::recursive_mutex;
using boost::lock_guard;
using boost::condition_variable;
using boost::unique_lock;
using boost::thread;
}
And do not forget to link against boost thread library.
There is a tutorial - http://llvm.org/docs/GettingStartedVS.html Example done in pure C. I can compile and link it. Without problem, really. But I need C++, not pure C. And here the difficulties begin.
For clang++ I use string like
"C:\..> clang++ -c hello.cpp -emit-llvm -o hello.bc"
then:
"C:\..> llc -filetype=obj hello.bc"
and
"C:\..> link hello.obj -defaultlib:libcmt -out:hello.exe"
there I get 14 errors LNK2001: unresolved external symbol
So, I need some tips. What I do wrong?
//-----------------
hello.cpp:
#include < iostream >
int main()
{
std::cout << "TEST\n" << std::endl;
return 0;
}
//-----------------
OS: Windows7.
UPD: Main question: how from .bc get .exe? (LLVM, Windows7)
You can use my GCC and Clang packages:
Download and extract them to the same directory. Clang will use GCC 4.6.3's libstdc++ and MinGW-w64's CRT. Call it like you would gcc.
Clang/LLVM cannot currently work with MSVC's C++ library, due to ABI issues. GCC's libstdc++ works quite well, though it has holes in surprising places (like std::to_string, <regex>, and <thread>).
Clang's Windows support is OK, but far from complete. You cannot for example dllexport whole C++ classes, unfortunately. And Win64 code generation is also not good enough to have a working C++ install (even in combination with GCC, like for 32-bit).