OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [libstdc++-v3/] [doc/] [xml/] [manual/] [using.xml] - Blame information for rev 833

Go to most recent revision | Details | Compare with Previous | View Log

Line No. Rev Author Line
1 742 jeremybenn
2
         xml:id="manual.intro.using" xreflabel="Using">
3
  Using
4
  
5
 
6
  
Command Options
7
 
8
    
9
      The set of features available in the GNU C++ library is shaped
10
      by
11
      several GCC
12
      Command Options. Options that impact libstdc++ are
13
      enumerated and detailed in the table below.
14
    
15
 
16
    
17
      By default, g++ is equivalent to  g++ -std=gnu++98. The standard library also defaults to this dialect.
18
    
19
 
20
 
21
C++ Command Options
22
 
23
24
25
26
 
27
  
28
    
29
      Option Flags
30
      Description
31
    
32
  
33
 
34
  
35
    
36
      -std=c++98
37
      Use the 1998 ISO C++ standard plus amendments.
38
    
39
 
40
    
41
      -std=gnu++98
42
      As directly above, with GNU extensions.
43
    
44
 
45
    
46
      -std=c++11
47
      Use the 2011 ISO C++ standard.
48
    
49
 
50
    
51
      -std=gnu++11
52
      As directly above, with GNU extensions.
53
    
54
 
55
    
56
      -fexceptions
57
      See exception-free dialect
58
    
59
 
60
    
61
      -frtti
62
      As above, but RTTI-free dialect.
63
    
64
 
65
    
66
      -pthread or -pthreads
67
      For ISO C++11 <thread>, <future>,
68
      <mutex>, or <condition_variable>.
69
    
70
 
71
    
72
      -fopenmp
73
      For parallel mode.
74
    
75
  
76
 
77
78
79
 
80
  
81
 
82
  
Headers
83
    
84
 
85
 
86
    
Header Files
87
 
88
 
89
   
90
     The C++ standard specifies the entire set of header files that
91
     must be available to all hosted implementations.  Actually, the
92
     word "files" is a misnomer, since the contents of the
93
     headers don't necessarily have to be in any kind of external
94
     file.  The only rule is that when one #include's a
95
     header, the contents of that header become available, no matter
96
     how.
97
   
98
 
99
   
100
   That said, in practice files are used.
101
   
102
 
103
   
104
     There are two main types of include files: header files related
105
     to a specific version of the ISO C++ standard (called Standard
106
     Headers), and all others (TR1, C++ ABI, and Extensions).
107
   
108
 
109
   
110
     Two dialects of standard headers are supported, corresponding to
111
     the 1998 standard as updated for 2003, and the current 2011 standard.
112
   
113
 
114
   
115
     C++98/03 include files. These are available in the default compilation mode, i.e. -std=c++98 or -std=gnu++98.
116
   
117
 
118
119
C++ 1998 Library Headers
120
 
121
122
123
124
125
126
127
128
129
algorithm
130
bitset
131
complex
132
deque
133
exception
134
135
136
fstream
137
functional
138
iomanip
139
ios
140
iosfwd
141
142
143
iostream
144
istream
145
iterator
146
limits
147
list
148
149
150
locale
151
map
152
memory
153
new
154
numeric
155
156
157
ostream
158
queue
159
set
160
sstream
161
stack
162
163
164
stdexcept
165
streambuf
166
string
167
utility
168
typeinfo
169
170
171
valarray
172
vector
173
174
175
176
177
 
178
179
180
C++ 1998 Library Headers for C Library Facilities
181
 
182
183
184
185
186
187
188
189
190
cassert
191
cerrno
192
cctype
193
cfloat
194
ciso646
195
196
197
climits
198
clocale
199
cmath
200
csetjmp
201
csignal
202
203
204
cstdarg
205
cstddef
206
cstdio
207
cstdlib
208
cstring
209
210
211
ctime
212
cwchar
213
cwctype
214
215
216
217
218
 
219
220
C++11 include files. These are only available in C++11 compilation
221
mode, i.e. -std=c++11 or -std=gnu++11.
222
223
 
224
225
226
C++ 2011 Library Headers
227
 
228
229
230
231
232
233
234
235
 
236
237
algorithm
238
array
239
bitset
240
chrono
241
complex
242
243
244
condition_variable
245
deque
246
exception
247
forward_list
248
fstream
249
250
251
functional
252
future
253
initalizer_list
254
iomanip
255
ios
256
257
258
iosfwd
259
iostream
260
istream
261
iterator
262
limits
263
264
265
list
266
locale
267
map
268
memory
269
mutex
270
271
272
new
273
numeric
274
ostream
275
queue
276
random
277
278
279
ratio
280
regex
281
set
282
sstream
283
stack
284
285
286
stdexcept
287
streambuf
288
string
289
system_error
290
thread
291
292
293
tuple
294
type_traits
295
typeinfo
296
unordered_map
297
unordered_set
298
299
300
utility
301
valarray
302
vector
303
304
 
305
306
307
308
 
309
310
 
311
312
C++ 2011 Library Headers for C Library Facilities
313
 
314
315
316
317
318
319
320
321
322
cassert
323
ccomplex
324
cctype
325
cerrno
326
cfenv
327
328
329
cfloat
330
cinttypes
331
ciso646
332
climits
333
clocale
334
335
336
cmath
337
csetjmp
338
csignal
339
cstdarg
340
cstdbool
341
342
343
cstddef
344
cstdint
345
cstdlib
346
cstdio
347
cstring
348
349
350
ctgmath
351
ctime
352
cuchar
353
cwchar
354
cwctype
355
356
357
358
359
 
360
 
361
362
  In addition, TR1 includes as:
363
364
 
365
366
C++ TR 1 Library Headers
367
 
368
369
370
371
372
373
374
375
 
376
377
tr1/array
378
tr1/complex
379
tr1/memory
380
tr1/functional
381
tr1/random
382
383
384
tr1/regex
385
tr1/tuple
386
tr1/type_traits
387
tr1/unordered_map
388
tr1/unordered_set
389
390
391
tr1/utility
392
393
 
394
395
396
397
 
398
399
 
400
 
401
402
C++ TR 1 Library Headers for C Library Facilities
403
 
404
405
406
407
408
409
410
411
 
412
413
tr1/ccomplex
414
tr1/cfenv
415
tr1/cfloat
416
tr1/cmath
417
tr1/cinttypes
418
419
420
tr1/climits
421
tr1/cstdarg
422
tr1/cstdbool
423
tr1/cstdint
424
tr1/cstdio
425
426
427
tr1/cstdlib
428
tr1/ctgmath
429
tr1/ctime
430
tr1/cwchar
431
tr1/cwctype
432
433
 
434
435
436
437
 
438
 
439
Decimal floating-point arithmetic is available if the C++
440
compiler supports scalar decimal floating-point types defined via
441
__attribute__((mode(SD|DD|LD))).
442
443
 
444
445
C++ TR 24733 Decimal Floating-Point Header
446
 
447
448
449
450
451
decimal/decimal
452
453
454
455
456
 
457
458
  Also included are files for the C++ ABI interface:
459
460
 
461
462
C++ ABI Headers
463
 
464
465
466
467
468
cxxabi.hcxxabi_forced.h
469
470
471
472
 
473
474
  And a large variety of extensions.
475
476
 
477
478
Extension Headers
479
 
480
481
482
483
484
485
486
487
 
488
489
ext/algorithm
490
ext/atomicity.h
491
ext/array_allocator.h
492
ext/bitmap_allocator.h
493
ext/cast.h
494
495
496
ext/codecvt_specializations.h
497
ext/concurrence.h
498
ext/debug_allocator.h
499
ext/enc_filebuf.h
500
ext/extptr_allocator.h
501
502
503
ext/functional
504
ext/iterator
505
ext/malloc_allocator.h
506
ext/memory
507
ext/mt_allocator.h
508
509
510
ext/new_allocator.h
511
ext/numeric
512
ext/numeric_traits.h
513
ext/pb_ds/assoc_container.h
514
ext/pb_ds/priority_queue.h
515
516
517
ext/pod_char_traits.h
518
ext/pool_allocator.h
519
ext/rb_tree
520
ext/rope
521
ext/slist
522
523
524
ext/stdio_filebuf.h
525
ext/stdio_sync_filebuf.h
526
ext/throw_allocator.h
527
ext/typelist.h
528
ext/type_traits.h
529
530
531
ext/vstring.h
532
533
 
534
535
536
537
 
538
539
 
540
541
Extension Debug Headers
542
 
543
544
545
546
547
548
549
550
 
551
552
debug/bitset
553
debug/deque
554
debug/list
555
debug/map
556
debug/set
557
558
 
559
560
debug/string
561
debug/unordered_map
562
debug/unordered_set
563
debug/vector
564
565
 
566
567
568
569
 
570
571
 
572
573
Extension Profile Headers
574
 
575
576
577
578
579
580
581
 
582
583
profile/bitset
584
profile/deque
585
profile/list
586
profile/map
587
588
 
589
590
profile/set
591
profile/unordered_map
592
profile/unordered_set
593
profile/vector
594
595
 
596
597
598
599
 
600
601
 
602
603
Extension Parallel Headers
604
 
605
606
607
608
609
610
parallel/algorithm
611
parallel/numeric
612
613
614
615
616
 
617
    
618
 
619
    
Mixing Headers
620
 
621
 
622
 A few simple rules.
623
624
 
625
First, mixing different dialects of the standard headers is not
626
possible. It's an all-or-nothing affair. Thus, code like
627
628
 
629
630
#include <array>
631
#include <functional>
632
633
 
634
Implies C++11 mode. To use the entities in <array>, the C++11
635
compilation mode must be used, which implies the C++11 functionality
636
(and deprecations) in <functional> will be present.
637
638
 
639
Second, the other headers can be included with either dialect of
640
the standard headers, although features and types specific to C++11
641
are still only enabled when in C++11 compilation mode. So, to use
642
rvalue references with __gnu_cxx::vstring, or to use the
643
debug-mode versions of std::unordered_map, one must use
644
the std=gnu++11 compiler flag. (Or std=c++11, of course.)
645
646
 
647
A special case of the second rule is the mixing of TR1 and C++11
648
facilities. It is possible (although not especially prudent) to
649
include both the TR1 version and the C++11 version of header in the
650
same translation unit:
651
652
 
653
654
#include <tr1/type_traits>
655
#include <type_traits>
656
657
 
658
 Several parts of C++11 diverge quite substantially from TR1 predecessors.
659
660
    
661
 
662
    
The C Headers and <code>namespace std</code>
663
 
664
 
665
666
        The standard specifies that if one includes the C-style header
667
        (<math.h> in this case), the symbols will be available
668
        in the global namespace and perhaps in
669
        namespace std:: (but this is no longer a firm
670
        requirement.) On the other hand, including the C++-style
671
        header (<cmath>) guarantees that the entities will be
672
        found in namespace std and perhaps in the global namespace.
673
      
674
 
675
676
Usage of C++-style headers is recommended, as then
677
C-linkage names can be disambiguated by explicit qualification, such
678
as by std::abort. In addition, the C++-style headers can
679
use function overloading to provide a simpler interface to certain
680
families of C-functions. For instance in <cmath>, the
681
function std::sin has overloads for all the builtin
682
floating-point types. This means that std::sin can be
683
used uniformly, instead of a combination
684
of std::sinf, std::sin,
685
and std::sinl.
686
687
    
688
 
689
    
Precompiled Headers
690
 
691
 
692
 
693
There are three base header files that are provided. They can be
694
used to precompile the standard headers and extensions into binary
695
files that may the be used to speed compiles that use these headers.
696
697
 
698
 
699
700
701
  stdc++.h
702
Includes all standard headers. Actual content varies depending on
703
language dialect.
704
705
706
 
707
708
  stdtr1c++.h
709
Includes all of <stdc++.h>, and adds all the TR1 headers.
710
711
712
 
713
extc++.h
714
Includes all of <stdtr1c++.h>, and adds all the Extension headers.
715
716
717
 
718
How to construct a .gch file from one of these base header files.
719
 
720
First, find the include directory for the compiler. One way to do
721
this is:
722
 
723
724
g++ -v hello.cc
725
 
726
#include <...> search starts here:
727
 /mnt/share/bld/H-x86-gcc.20071201/include/c++/4.3.0
728
...
729
End of search list.
730
731
 
732
 
733
Then, create a precompiled header file with the same flags that
734
will be used to compile other projects.
735
 
736
737
g++ -Winvalid-pch -x c++-header -g -O2 -o ./stdc++.h.gch /mnt/share/bld/H-x86-gcc.20071201/include/c++/4.3.0/x86_64-unknown-linux-gnu/bits/stdc++.h
738
739
 
740
The resulting file will be quite large: the current size is around
741
thirty megabytes. 
742
 
743
How to use the resulting file.
744
 
745
746
g++ -I. -include stdc++.h  -H -g -O2 hello.cc
747
748
 
749
Verification that the PCH file is being used is easy:
750
 
751
752
g++ -Winvalid-pch -I. -include stdc++.h -H -g -O2 hello.cc -o test.exe
753
! ./stdc++.h.gch
754
. /mnt/share/bld/H-x86-gcc.20071201/include/c++/4.3.0/iostream
755
. /mnt/share/bld/H-x86-gcc.20071201include/c++/4.3.0/string
756
757
 
758
The exclamation point to the left of the stdc++.h.gch listing means that the generated PCH file was used, and thus the 
759
760
 
761
 Detailed information about creating precompiled header files can be found in the GCC documentation.
762
763
 
764
    
765
  
766
 
767
 
768
  
Macros
769
    
770
 
771
 
772
   
773
     All library macros begin with _GLIBCXX_.
774
   
775
 
776
   
777
     Furthermore, all pre-processor macros, switches, and
778
      configuration options are gathered in the
779
      file c++config.h, which
780
      is generated during the libstdc++ configuration and build
781
      process. This file is then included when needed by files part of
782
      the public libstdc++ API, like <ios>. Most of these macros
783
      should not be used by consumers of libstdc++, and are reserved
784
      for internal implementation use. These macros cannot
785
      be redefined.
786
   
787
 
788
   
789
     A select handful of macros control libstdc++ extensions and extra
790
      features, or provide versioning information for the API.  Only
791
      those macros listed below are offered for consideration by the
792
      general public.
793
   
794
 
795
   Below is the macro which users may check for library version
796
      information. 
797
 
798
    
799
    
800
      __GLIBCXX__
801
      
802
        The current version of
803
    libstdc++ in compressed ISO date format, form of an unsigned
804
    long. For details on the value of this particular macro for a
805
    particular release, please consult this 
806
    document.
807
    
808
    
809
    
810
    
811
 
812
   Below are the macros which users may change with #define/#undef or
813
      with -D/-U compiler flags.  The default state of the symbol is
814
      listed.
815
 
816
   Configurable (or Not configurable) means
817
      that the symbol is initially chosen (or not) based on
818
      --enable/--disable options at library build and configure time
819
      (documented here), with the
820
      various --enable/--disable choices being translated to
821
      #define/#undef).
822
   
823
 
824
    ABI means that changing from the default value may
825
  mean changing the ABI of compiled code. In other words, these
826
  choices control code which has already been compiled (i.e., in a
827
  binary such as libstdc++.a/.so).  If you explicitly #define or
828
  #undef these macros, the headers may see different code
829
  paths, but the libraries which you link against will not.
830
  Experimenting with different values with the expectation of
831
  consistent linkage requires changing the config headers before
832
  building/installing the library.
833
   
834
 
835
    
836
    _GLIBCXX_USE_DEPRECATED
837
    
838
      
839
        Defined by default. Not configurable. ABI-changing. Turning this off
840
        removes older ARM-style iostreams code, and other anachronisms
841
        from the API.  This macro is dependent on the version of the
842
        standard being tracked, and as a result may give different results for
843
        -std=c++98 and -std=c++11. This may
844
        be useful in updating old C++ code which no longer meet the
845
        requirements of the language, or for checking current code
846
        against new language standards.
847
    
848
    
849
 
850
    _GLIBCXX_FORCE_NEW
851
    
852
      
853
        Undefined by default. When defined, memory allocation and
854
        allocators controlled by libstdc++ call operator new/delete
855
        without caching and pooling. Configurable via
856
        --enable-libstdcxx-allocator. ABI-changing.
857
      
858
    
859
 
860
 
861
    _GLIBCXX_CONCEPT_CHECKS
862
    
863
      
864
        Undefined by default.  Configurable via
865
        --enable-concept-checks.  When defined, performs
866
        compile-time checking on certain template instantiations to
867
        detect violations of the requirements of the standard.  This
868
        is described in more detail here.
869
      
870
    
871
 
872
    _GLIBCXX_DEBUG
873
    
874
      
875
        Undefined by default. When defined, compiles user code using
876
    the debug mode.
877
      
878
    
879
    _GLIBCXX_DEBUG_PEDANTIC
880
    
881
      
882
        Undefined by default. When defined while compiling with
883
    the debug mode, makes
884
    the debug mode extremely picky by making the use of libstdc++
885
    extensions and libstdc++-specific behavior into errors.
886
      
887
    
888
    _GLIBCXX_PARALLEL
889
    
890
      Undefined by default. When defined, compiles user code
891
    using the parallel
892
    mode.
893
      
894
    
895
 
896
    _GLIBCXX_PROFILE
897
    
898
      Undefined by default. When defined, compiles user code
899
    using the profile
900
    mode.
901
      
902
    
903
    
904
 
905
  
906
 
907
  
Namespaces
908
    
909
 
910
 
911
    
Available Namespaces
912
 
913
 
914
 
915
 
916
 There are three main namespaces.
917
918
 
919
920
  std
921
The ISO C++ standards specify that "all library entities are defined
922
within namespace std." This includes namespaces nested
923
within namespace std, such as namespace
924
std::tr1.
925
926
927
abi
928
Specified by the C++ ABI. This ABI specifies a number of type and
929
function APIs supplemental to those required by the ISO C++ Standard,
930
but necessary for interoperability.
931
932
933
 
934
__gnu_
935
Indicating one of several GNU extensions. Choices
936
include __gnu_cxx, __gnu_debug, __gnu_parallel,
937
and __gnu_pbds.
938
939
940
 
941
 A complete list of implementation namespaces (including namespace contents) is available in the generated source documentation.
942
943
 
944
 
945
    
946
 
947
    
namespace std
948
 
949
 
950
 
951
952
      One standard requirement is that the library components are defined
953
      in namespace std::. Thus, in order to use these types or
954
      functions, one must do one of two things:
955
956
 
957
958
  put a kind of using-declaration in your source
959
(either using namespace std; or i.e. using
960
std::string;) This approach works well for individual source files, but
961
should not be used in a global context, like header files.
962
           use a fully
963
qualified name for each library symbol
964
(i.e. std::string, std::cout) Always can be
965
used, and usually enhanced, by strategic use of typedefs. (In the
966
cases where the qualified verbiage becomes unwieldy.)
967
          
968
        
969
970
 
971
    
972
 
973
    
Using Namespace Composition
974
 
975
 
976
977
Best practice in programming suggests sequestering new data or
978
functionality in a sanely-named, unique namespace whenever
979
possible. This is considered an advantage over dumping everything in
980
the global namespace, as then name look-up can be explicitly enabled or
981
disabled as above, symbols are consistently mangled without repetitive
982
naming prefixes or macros, etc.
983
984
 
985
For instance, consider a project that defines most of its classes in namespace gtk. It is possible to
986
        adapt namespace gtk to namespace std by using a C++-feature called
987
        namespace composition. This is what happens if
988
        a using-declaration is put into a
989
        namespace-definition: the imported symbol(s) gets imported into the
990
        currently active namespace(s). For example:
991
992
993
namespace gtk
994
{
995
  using std::string;
996
  using std::tr1::array;
997
 
998
  class Window { ... };
999
}
1000
1001
1002
        In this example, std::string gets imported into
1003
        namespace gtk.  The result is that use of
1004
        std::string inside namespace gtk can just use string, without the explicit qualification.
1005
        As an added bonus,
1006
        std::string does not get imported into
1007
        the global namespace.  Additionally, a more elaborate arrangement can be made for backwards compatibility and portability, whereby the
1008
        using-declarations can wrapped in macros that
1009
        are set based on autoconf-tests to either "" or i.e. using
1010
          std::string; (depending on whether the system has
1011
        libstdc++ in std:: or not).  (ideas from
1012
        Llewelly and Karl Nelson)
1013
1014
 
1015
 
1016
    
1017
  
1018
 
1019
  
Linking
1020
    
1021
 
1022
 
1023
    
Almost Nothing
1024
 
1025
      
1026
        Or as close as it gets: freestanding. This is a minimal
1027
        configuration, with only partial support for the standard
1028
        library. Assume only the following header files can be used:
1029
      
1030
 
1031
      
1032
        
1033
          
1034
            cstdarg
1035
          
1036
        
1037
 
1038
        
1039
          
1040
          cstddef
1041
          
1042
        
1043
 
1044
        
1045
          
1046
          cstdlib
1047
          
1048
        
1049
 
1050
        
1051
          
1052
          exception
1053
          
1054
        
1055
 
1056
        
1057
          
1058
          limits
1059
          
1060
        
1061
 
1062
        
1063
          
1064
          new
1065
          
1066
        
1067
 
1068
        
1069
          
1070
          exception
1071
          
1072
        
1073
 
1074
        
1075
          
1076
          typeinfo
1077
          
1078
        
1079
      
1080
 
1081
      
1082
        In addition, throw in
1083
      
1084
 
1085
      
1086
        
1087
          
1088
          cxxabi.h.
1089
          
1090
        
1091
      
1092
 
1093
      
1094
        In the
1095
        C++11 dialect add
1096
      
1097
 
1098
      
1099
        
1100
          
1101
          initializer_list
1102
          
1103
        
1104
        
1105
          
1106
          type_traits
1107
          
1108
        
1109
      
1110
 
1111
       There exists a library that offers runtime support for
1112
        just these headers, and it is called
1113
        libsupc++.a. To use it, compile with gcc instead of g++, like so:
1114
      
1115
 
1116
      
1117
        gcc foo.cc -lsupc++
1118
      
1119
 
1120
      
1121
        No attempt is made to verify that only the minimal subset
1122
        identified above is actually used at compile time. Violations
1123
        are diagnosed as undefined symbols at link time.
1124
      
1125
    
1126
 
1127
    
Finding Dynamic or Shared Libraries
1128
 
1129
 
1130
    
1131
      If the only library built is the static library
1132
      (libstdc++.a), or if
1133
      specifying static linking, this section is can be skipped.  But
1134
      if building or using a shared library
1135
      (libstdc++.so), then
1136
      additional location information will need to be provided.
1137
    
1138
    
1139
      But how?
1140
    
1141
    
1142
A quick read of the relevant part of the GCC
1143
      manual, Compiling
1144
      C++ Programs, specifies linking against a C++
1145
      library. More details from the
1146
      GCC FAQ,
1147
      which states GCC does not, by default, specify a
1148
      location so that the dynamic linker can find dynamic libraries at
1149
      runtime.
1150
    
1151
    
1152
      Users will have to provide this information.
1153
    
1154
    
1155
      Methods vary for different platforms and different styles, and
1156
      are printed to the screen during installation. To summarize:
1157
    
1158
    
1159
      
1160
        
1161
          At runtime set LD_LIBRARY_PATH in your
1162
          environment correctly, so that the shared library for
1163
          libstdc++ can be found and loaded.  Be certain that you
1164
          understand all of the other implications and behavior
1165
          of LD_LIBRARY_PATH first.
1166
        
1167
 
1168
      
1169
      
1170
        
1171
          Compile the path to find the library at runtime into the
1172
          program.  This can be done by passing certain options to
1173
          g++, which will in turn pass them on to
1174
          the linker.  The exact format of the options is dependent on
1175
          which linker you use:
1176
        
1177
        
1178
          
1179
            
1180
              GNU ld (default on GNU/Linux):
1181
              -Wl,-rpath,destdir/lib
1182
            
1183
          
1184
          
1185
            
1186
              IRIX ld:
1187
              -Wl,-rpath,destdir/lib
1188
            
1189
          
1190
          
1191
          
1192
            Solaris ld:
1193
            -Wl,-Rdestdir/lib
1194
          
1195
          
1196
        
1197
      
1198
      
1199
        
1200
          Some linkers allow you to specify the path to the library by
1201
          setting LD_RUN_PATH in your environment
1202
          when linking.
1203
        
1204
      
1205
      
1206
        
1207
          On some platforms the system administrator can configure the
1208
          dynamic linker to always look for libraries in
1209
          destdir/lib, for example
1210
          by using the ldconfig utility on GNU/Linux
1211
          or the crle utility on Solaris. This is a
1212
          system-wide change which can make the system unusable so if you
1213
          are unsure then use one of the other methods described above.
1214
        
1215
      
1216
    
1217
    
1218
      Use the ldd utility on the linked executable
1219
      to show
1220
      which libstdc++.so
1221
      library the system will get at runtime.
1222
    
1223
    
1224
      A libstdc++.la file is
1225
      also installed, for use with Libtool.  If you use Libtool to
1226
      create your executables, these details are taken care of for
1227
      you.
1228
    
1229
    
1230
  
1231
 
1232
 
1233
  
Concurrency
1234
    
1235
 
1236
 
1237
   This section discusses issues surrounding the proper compilation
1238
      of multithreaded applications which use the Standard C++
1239
      library.  This information is GCC-specific since the C++
1240
      standard does not address matters of multithreaded applications.
1241
   
1242
 
1243
    
Prerequisites
1244
 
1245
 
1246
   All normal disclaimers aside, multithreaded C++ application are
1247
      only supported when libstdc++ and all user code was built with
1248
      compilers which report (via  gcc/g++ -v ) the same thread
1249
      model and that model is not single.  As long as your
1250
      final application is actually single-threaded, then it should be
1251
      safe to mix user code built with a thread model of
1252
      single with a libstdc++ and other C++ libraries built
1253
      with another thread model useful on the platform.  Other mixes
1254
      may or may not work but are not considered supported.  (Thus, if
1255
      you distribute a shared C++ library in binary form only, it may
1256
      be best to compile it with a GCC configured with
1257
      --enable-threads for maximal interchangeability and usefulness
1258
      with a user population that may have built GCC with either
1259
      --enable-threads or --disable-threads.)
1260
   
1261
   When you link a multithreaded application, you will probably
1262
      need to add a library or flag to g++.  This is a very
1263
      non-standardized area of GCC across ports.  Some ports support a
1264
      special flag (the spelling isn't even standardized yet) to add
1265
      all required macros to a compilation (if any such flags are
1266
      required then you must provide the flag for all compilations not
1267
      just linking) and link-library additions and/or replacements at
1268
      link time.  The documentation is weak.  Here is a quick summary
1269
      to display how ad hoc this is: On Solaris, both -pthreads and
1270
      -threads (with subtly different meanings) are honored.  On OSF,
1271
      -pthread and -threads (with subtly different meanings) are
1272
      honored.  On GNU/Linux x86, -pthread is honored.  On FreeBSD,
1273
      -pthread is honored.  Some other ports use other switches.
1274
      AFAIK, none of this is properly documented anywhere other than
1275
      in ``gcc -dumpspecs'' (look at lib and cpp entries).
1276
   
1277
 
1278
    
1279
 
1280
    
Thread Safety
1281
 
1282
 
1283
1284
In the terms of the 2011 C++ standard a thread-safe program is one which
1285
does not perform any conflicting non-atomic operations on memory locations
1286
and so does not contain any data races.
1287
The standard places requirements on the library to ensure that no data
1288
races are caused by the library itself or by programs which use the
1289
library correctly (as described below).
1290
The C++11 memory model and library requirements are a more formal version
1291
of the SGI STL definition of thread safety, which the library used
1292
prior to the 2011 standard.
1293
1294
 
1295
 
1296
      The library strives to be thread-safe when all of the following
1297
         conditions are met:
1298
      
1299
      
1300
       
1301
       The system's libc is itself thread-safe,
1302
       
1303
       
1304
       
1305
         
1306
           The compiler in use reports a thread model other than
1307
           'single'. This can be tested via output from gcc
1308
           -v. Multi-thread capable versions of gcc output
1309
           something like this:
1310
         
1311
1312
%gcc -v
1313
Using built-in specs.
1314
...
1315
Thread model: posix
1316
gcc version 4.1.2 20070925 (Red Hat 4.1.2-33)
1317
1318
 
1319
Look for "Thread model" lines that aren't equal to "single."
1320
       
1321
       
1322
       
1323
         Requisite command-line flags are used for atomic operations
1324
         and threading. Examples of this include -pthread
1325
         and -march=native, although specifics vary
1326
         depending on the host environment. See Machine
1327
         Dependent Options.
1328
       
1329
       
1330
       
1331
         
1332
           An implementation of atomicity.h functions
1333
           exists for the architecture in question. See the internals documentation for more details.
1334
       
1335
       
1336
 
1337
      
1338
 
1339
      The user code must guard against concurrent function calls which
1340
         access any particular library object's state when one or more of
1341
         those accesses modifies the state. An object will be modified by
1342
         invoking a non-const member function on it or passing it as a
1343
         non-const argument to a library function. An object will not be
1344
         modified by invoking a const member function on it or passing it to
1345
         a function as a pointer- or reference-to-const.
1346
         Typically, the application
1347
         programmer may infer what object locks must be held based on the
1348
         objects referenced in a function call and whether the objects are
1349
         accessed as const or non-const.  Without getting
1350
         into great detail, here is an example which requires user-level
1351
         locks:
1352
      
1353
      
1354
     library_class_a shared_object_a;
1355
 
1356
     void thread_main () {
1357
       library_class_b *object_b = new library_class_b;
1358
       shared_object_a.add_b (object_b);   // must hold lock for shared_object_a
1359
       shared_object_a.mutate ();          // must hold lock for shared_object_a
1360
     }
1361
 
1362
     // Multiple copies of thread_main() are started in independent threads.
1363
      Under the assumption that object_a and object_b are never exposed to
1364
         another thread, here is an example that does not require any
1365
         user-level locks:
1366
      
1367
      
1368
     void thread_main () {
1369
       library_class_a object_a;
1370
       library_class_b *object_b = new library_class_b;
1371
       object_a.add_b (object_b);
1372
       object_a.mutate ();
1373
     } 
1374
 
1375
      All library types are safe to use in a multithreaded program
1376
         if objects are not shared between threads or as
1377
         long each thread carefully locks out access by any other
1378
         thread while it modifies any object visible to another thread.
1379
         Unless otherwise documented, the only exceptions to these rules
1380
         are atomic operations on the types in
1381
         <atomic>
1382
         and lock/unlock operations on the standard mutex types in
1383
         <mutex>. These
1384
         atomic operations allow concurrent accesses to the same object
1385
         without introducing data races.
1386
      
1387
 
1388
      The following member functions of standard containers can be
1389
         considered to be const for the purposes of avoiding data races:
1390
         begin, end, rbegin, rend,
1391
         front, back, data,
1392
         find, lower_bound, upper_bound,
1393
         equal_range, at
1394
         and, except in associative or unordered associative containers,
1395
         operator[]. In other words, although they are non-const
1396
         so that they can return mutable iterators, those member functions
1397
         will not modify the container.
1398
         Accessing an iterator might cause a non-modifying access to
1399
         the container the iterator refers to (for example incrementing a
1400
         list iterator must access the pointers between nodes, which are part
1401
         of the container and so conflict with other accesses to the container).
1402
      
1403
 
1404
      Programs which follow the rules above will not encounter data
1405
         races in library code, even when using library types which share
1406
         state between distinct objects.  In the example below the
1407
         shared_ptr objects share a reference count, but
1408
         because the code does not perform any non-const operations on the
1409
         globally-visible object, the library ensures that the reference
1410
         count updates are atomic and do not introduce data races:
1411
      
1412
      
1413
    std::shared_ptr<int> global_sp;
1414
 
1415
    void thread_main() {
1416
      auto local_sp = global_sp;  // OK, copy constructor's parameter is reference-to-const
1417
 
1418
      int i = *global_sp;         // OK, operator* is const
1419
      int j = *local_sp;          // OK, does not operate on global_sp
1420
 
1421
      // *global_sp = 2;          // NOT OK, modifies int visible to other threads
1422
      // *local_sp = 2;           // NOT OK, modifies int visible to other threads
1423
 
1424
      // global_sp.reset();       // NOT OK, reset is non-const
1425
      local_sp.reset();           // OK, does not operate on global_sp
1426
    }
1427
 
1428
    int main() {
1429
      global_sp.reset(new int(1));
1430
      std::thread t1(thread_main);
1431
      std::thread t2(thread_main);
1432
      t1.join();
1433
      t2.join();
1434
    }
1435
      
1436
 
1437
      For further details of the C++11 memory model see Hans-J. Boehm's
1438
      Threads
1439
      and memory model for C++ pages, particularly the introduction
1440
      and FAQ.
1441
      
1442
 
1443
  
1444
  
Atomics
1445
 
1446
    
1447
    
1448
  
1449
 
1450
    
IO
1451
 
1452
     This gets a bit tricky.  Please read carefully, and bear with me.
1453
   
1454
 
1455
    
Structure
1456
 
1457
   A wrapper
1458
      type called __basic_file provides our abstraction layer
1459
      for the std::filebuf classes.  Nearly all decisions dealing
1460
      with actual input and output must be made in __basic_file.
1461
   
1462
   A generic locking mechanism is somewhat in place at the filebuf layer,
1463
      but is not used in the current code.  Providing locking at any higher
1464
      level is akin to providing locking within containers, and is not done
1465
      for the same reasons (see the links above).
1466
   
1467
    
1468
 
1469
    
Defaults
1470
 
1471
   The __basic_file type is simply a collection of small wrappers around
1472
      the C stdio layer (again, see the link under Structure).  We do no
1473
      locking ourselves, but simply pass through to calls to fopen,
1474
      fwrite, and so forth.
1475
   
1476
   So, for 3.0, the question of "is multithreading safe for I/O"
1477
      must be answered with, "is your platform's C library threadsafe
1478
      for I/O?"  Some are by default, some are not; many offer multiple
1479
      implementations of the C library with varying tradeoffs of threadsafety
1480
      and efficiency.  You, the programmer, are always required to take care
1481
      with multiple threads.
1482
   
1483
   (As an example, the POSIX standard requires that C stdio FILE*
1484
       operations are atomic.  POSIX-conforming C libraries (e.g, on Solaris
1485
       and GNU/Linux) have an internal mutex to serialize operations on
1486
       FILE*s.  However, you still need to not do stupid things like calling
1487
       fclose(fs) in one thread followed by an access of
1488
       fs in another.)
1489
   
1490
   So, if your platform's C library is threadsafe, then your
1491
      fstream I/O operations will be threadsafe at the lowest
1492
      level.  For higher-level operations, such as manipulating the data
1493
      contained in the stream formatting classes (e.g., setting up callbacks
1494
      inside an std::ofstream), you need to guard such accesses
1495
      like any other critical shared resource.
1496
   
1497
    
1498
 
1499
    
Future
1500
 
1501
    A
1502
      second choice may be available for I/O implementations:  libio.  This is
1503
      disabled by default, and in fact will not currently work due to other
1504
      issues.  It will be revisited, however.
1505
   
1506
   The libio code is a subset of the guts of the GNU libc (glibc) I/O
1507
      implementation.  When libio is in use, the __basic_file
1508
      type is basically derived from FILE.  (The real situation is more
1509
      complex than that... it's derived from an internal type used to
1510
      implement FILE.  See libio/libioP.h to see scary things done with
1511
      vtbls.)  The result is that there is no "layer" of C stdio
1512
      to go through; the filebuf makes calls directly into the same
1513
      functions used to implement fread, fwrite,
1514
      and so forth, using internal data structures.  (And when I say
1515
      "makes calls directly," I mean the function is literally
1516
      replaced by a jump into an internal function.  Fast but frightening.
1517
      *grin*)
1518
   
1519
   Also, the libio internal locks are used.  This requires pulling in
1520
      large chunks of glibc, such as a pthreads implementation, and is one
1521
      of the issues preventing widespread use of libio as the libstdc++
1522
      cstdio implementation.
1523
   
1524
   But we plan to make this work, at least as an option if not a future
1525
      default.  Platforms running a copy of glibc with a recent-enough
1526
      version will see calls from libstdc++ directly into the glibc already
1527
      installed.  For other platforms, a copy of the libio subsection will
1528
      be built and included in libstdc++.
1529
   
1530
    
1531
 
1532
    
Alternatives
1533
 
1534
   Don't forget that other cstdio implementations are possible.  You could
1535
      easily write one to perform your own forms of locking, to solve your
1536
      "interesting" problems.
1537
   
1538
    
1539
 
1540
    
1541
 
1542
    
Containers
1543
 
1544
 
1545
   This section discusses issues surrounding the design of
1546
      multithreaded applications which use Standard C++ containers.
1547
      All information in this section is current as of the gcc 3.0
1548
      release and all later point releases.  Although earlier gcc
1549
      releases had a different approach to threading configuration and
1550
      proper compilation, the basic code design rules presented here
1551
      were similar.  For information on all other aspects of
1552
      multithreading as it relates to libstdc++, including details on
1553
      the proper compilation of threaded code (and compatibility between
1554
      threaded and non-threaded code), see Chapter 17.
1555
   
1556
   Two excellent pages to read when working with the Standard C++
1557
      containers and threads are
1558
      SGI's
1559
      http://www.sgi.com/tech/stl/thread_safety.html and
1560
      SGI's
1561
      http://www.sgi.com/tech/stl/Allocators.html.
1562
   
1563
   However, please ignore all discussions about the user-level
1564
      configuration of the lock implementation inside the STL
1565
      container-memory allocator on those pages.  For the sake of this
1566
      discussion, libstdc++ configures the SGI STL implementation,
1567
      not you.  This is quite different from how gcc pre-3.0 worked.
1568
      In particular, past advice was for people using g++ to
1569
      explicitly define _PTHREADS or other macros or port-specific
1570
      compilation options on the command line to get a thread-safe
1571
      STL.  This is no longer required for any port and should no
1572
      longer be done unless you really know what you are doing and
1573
      assume all responsibility.
1574
   
1575
   Since the container implementation of libstdc++ uses the SGI
1576
      code, we use the same definition of thread safety as SGI when
1577
      discussing design.  A key point that beginners may miss is the
1578
      fourth major paragraph of the first page mentioned above
1579
      (For most clients...), which points out that
1580
      locking must nearly always be done outside the container, by
1581
      client code (that'd be you, not us).  There is a notable
1582
      exceptions to this rule.  Allocators called while a container or
1583
      element is constructed uses an internal lock obtained and
1584
      released solely within libstdc++ code (in fact, this is the
1585
      reason STL requires any knowledge of the thread configuration).
1586
   
1587
   For implementing a container which does its own locking, it is
1588
      trivial to provide a wrapper class which obtains the lock (as
1589
      SGI suggests), performs the container operation, and then
1590
      releases the lock.  This could be templatized to a certain
1591
      extent, on the underlying container and/or a locking
1592
      mechanism.  Trying to provide a catch-all general template
1593
      solution would probably be more trouble than it's worth.
1594
   
1595
   The library implementation may be configured to use the
1596
      high-speed caching memory allocator, which complicates thread
1597
      safety issues. For all details about how to globally override
1598
      this at application run-time
1599
      see here. Also
1600
      useful are details
1601
      on allocator
1602
      options and capabilities.
1603
   
1604
 
1605
    
1606
1607
 
1608
1609
1610
1611
 
1612
1613
1614
1615
 
1616

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.