1 // Copyright (c) 2006, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 
30 // ---
31 // Revamped and reorganized by Craig Silverstein
32 //
33 // This is the file that should be included by any file which declares
34 // or defines a command line flag or wants to parse command line flags
35 // or print a program usage message (which will include information about
36 // flags).  Executive summary, in the form of an example foo.cc file:
37 //
38 //    #include "foo.h"         // foo.h has a line "DECLARE_int32(start);"
39 //    #include "validators.h"  // hypothetical file defining ValidateIsFile()
40 //
41 //    DEFINE_int32(end, 1000, "The last record to read");
42 //
43 //    DEFINE_string(filename, "my_file.txt", "The file to read");
44 //    // Crash if the specified file does not exist.
45 //    static bool dummy = RegisterFlagValidator(&FLAGS_filename,
46 //                                              &ValidateIsFile);
47 //
48 //    DECLARE_bool(verbose); // some other file has a DEFINE_bool(verbose, ...)
49 //
50 //    void MyFunc() {
51 //      if (FLAGS_verbose) printf("Records %d-%d\n", FLAGS_start, FLAGS_end);
52 //    }
53 //
54 //    Then, at the command-line:
55 //       ./foo --noverbose --start=5 --end=100
56 //
57 // For more details, see
58 //    doc/gflags.html
59 //
60 // --- A note about thread-safety:
61 //
62 // We describe many functions in this routine as being thread-hostile,
63 // thread-compatible, or thread-safe.  Here are the meanings we use:
64 //
65 // thread-safe: it is safe for multiple threads to call this routine
66 //   (or, when referring to a class, methods of this class)
67 //   concurrently.
68 // thread-hostile: it is not safe for multiple threads to call this
69 //   routine (or methods of this class) concurrently.  In gflags,
70 //   most thread-hostile routines are intended to be called early in,
71 //   or even before, main() -- that is, before threads are spawned.
72 // thread-compatible: it is safe for multiple threads to read from
73 //   this variable (when applied to variables), or to call const
74 //   methods of this class (when applied to classes), as long as no
75 //   other thread is writing to the variable or calling non-const
76 //   methods of this class.
77 
78 #ifndef BASE_COMMANDLINEFLAGS_H_
79 #define BASE_COMMANDLINEFLAGS_H_
80 
81 #include <string>
82 #include <vector>
83 #include <gflags/gflags_declare.h>    // IWYU pragma: export
84 namespace google {
85 
86 //
87 // NOTE: all functions below MUST have an explicit 'extern' before
88 // them.  Our automated opensourcing tools use this as a signal to do
89 // appropriate munging for windows, which needs to add GFLAGS_DLL_DECL.
90 //
91 #if defined(_MSC_VER) && !defined(GFLAGS_DLL_DECL)
92 # define GFLAGS_DLL_DECL  __declspec(dllimport)
93 #endif
94 #if defined(_MSC_VER) && !defined(GFLAGS_DLL_DEFINE_FLAG)
95 # define GFLAGS_DLL_DEFINE_FLAG  __declspec(dllexport)
96 #endif
97 
98 
99 // --------------------------------------------------------------------
100 // To actually define a flag in a file, use DEFINE_bool,
101 // DEFINE_string, etc. at the bottom of this file.  You may also find
102 // it useful to register a validator with the flag.  This ensures that
103 // when the flag is parsed from the commandline, or is later set via
104 // SetCommandLineOption, we call the validation function. It is _not_
105 // called when you assign the value to the flag directly using the = operator.
106 //
107 // The validation function should return true if the flag value is valid, and
108 // false otherwise. If the function returns false for the new setting of the
109 // flag, the flag will retain its current value. If it returns false for the
110 // default value, ParseCommandLineFlags() will die.
111 //
112 // This function is safe to call at global construct time (as in the
113 // example below).
114 //
115 // Example use:
116 //    static bool ValidatePort(const char* flagname, int32 value) {
117 //       if (value > 0 && value < 32768)   // value is ok
118 //         return true;
119 //       printf("Invalid value for --%s: %d\n", flagname, (int)value);
120 //       return false;
121 //    }
122 //    DEFINE_int32(port, 0, "What port to listen on");
123 //    static bool dummy = RegisterFlagValidator(&FLAGS_port, &ValidatePort);
124 
125 // Returns true if successfully registered, false if not (because the
126 // first argument doesn't point to a command-line flag, or because a
127 // validator is already registered for this flag).
128 extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const bool* flag,
129                                   bool (*validate_fn)(const char*, bool));
130 extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const int32* flag,
131                                   bool (*validate_fn)(const char*, int32));
132 extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const int64* flag,
133                                   bool (*validate_fn)(const char*, int64));
134 extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const uint64* flag,
135                                   bool (*validate_fn)(const char*, uint64));
136 extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const double* flag,
137                                   bool (*validate_fn)(const char*, double));
138 extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const std::string* flag,
139                                   bool (*validate_fn)(const char*,
140                                                       const std::string&));
141 
142 
143 // --------------------------------------------------------------------
144 // These methods are the best way to get access to info about the
145 // list of commandline flags.  Note that these routines are pretty slow.
146 //   GetAllFlags: mostly-complete info about the list, sorted by file.
147 //   ShowUsageWithFlags: pretty-prints the list to stdout (what --help does)
148 //   ShowUsageWithFlagsRestrict: limit to filenames with restrict as a substr
149 //
150 // In addition to accessing flags, you can also access argv[0] (the program
151 // name) and argv (the entire commandline), which we sock away a copy of.
152 // These variables are static, so you should only set them once.
153 
154 struct GFLAGS_DLL_DECL CommandLineFlagInfo {
155   std::string name;            // the name of the flag
156   std::string type;            // the type of the flag: int32, etc
157   std::string description;     // the "help text" associated with the flag
158   std::string current_value;   // the current value, as a string
159   std::string default_value;   // the default value, as a string
160   std::string filename;        // 'cleaned' version of filename holding the flag
161   bool has_validator_fn;  // true if RegisterFlagValidator called on this flag
162   bool is_default;        // true if the flag has the default value and
163                           // has not been set explicitly from the cmdline
164                           // or via SetCommandLineOption
165   const void* flag_ptr;   // pointer to the flag's current value (i.e. FLAGS_foo)
166 };
167 
168 // Using this inside of a validator is a recipe for a deadlock.
169 // TODO(user) Fix locking when validators are running, to make it safe to
170 // call validators during ParseAllFlags.
171 // Also make sure then to uncomment the corresponding unit test in
172 // gflags_unittest.sh
173 extern GFLAGS_DLL_DECL void GetAllFlags(std::vector<CommandLineFlagInfo>* OUTPUT);
174 // These two are actually defined in gflags_reporting.cc.
175 extern GFLAGS_DLL_DECL void ShowUsageWithFlags(const char *argv0);  // what --help does
176 extern GFLAGS_DLL_DECL void ShowUsageWithFlagsRestrict(const char *argv0, const char *restrict);
177 
178 // Create a descriptive string for a flag.
179 // Goes to some trouble to make pretty line breaks.
180 extern GFLAGS_DLL_DECL std::string DescribeOneFlag(const CommandLineFlagInfo& flag);
181 
182 // Thread-hostile; meant to be called before any threads are spawned.
183 extern GFLAGS_DLL_DECL void SetArgv(int argc, const char** argv);
184 
185 // The following functions are thread-safe as long as SetArgv() is
186 // only called before any threads start.
187 extern GFLAGS_DLL_DECL const std::vector<std::string>& GetArgvs();
188 extern GFLAGS_DLL_DECL const char* GetArgv();                 // all of argv as a string
189 extern GFLAGS_DLL_DECL const char* GetArgv0();                // only argv0
190 extern GFLAGS_DLL_DECL uint32 GetArgvSum();                   // simple checksum of argv
191 extern GFLAGS_DLL_DECL const char* ProgramInvocationName();   // argv0, or "UNKNOWN" if not set
192 extern GFLAGS_DLL_DECL const char* ProgramInvocationShortName();   // basename(argv0)
193 
194 // ProgramUsage() is thread-safe as long as SetUsageMessage() is only
195 // called before any threads start.
196 extern GFLAGS_DLL_DECL const char* ProgramUsage();            // string set by SetUsageMessage()
197 
198 // VersionString() is thread-safe as long as SetVersionString() is only
199 // called before any threads start.
200 extern GFLAGS_DLL_DECL const char* VersionString();          // string set by SetVersionString()
201 
202 
203 
204 // --------------------------------------------------------------------
205 // Normally you access commandline flags by just saying "if (FLAGS_foo)"
206 // or whatever, and set them by calling "FLAGS_foo = bar" (or, more
207 // commonly, via the DEFINE_foo macro).  But if you need a bit more
208 // control, we have programmatic ways to get/set the flags as well.
209 // These programmatic ways to access flags are thread-safe, but direct
210 // access is only thread-compatible.
211 
212 // Return true iff the flagname was found.
213 // OUTPUT is set to the flag's value, or unchanged if we return false.
214 extern GFLAGS_DLL_DECL bool GetCommandLineOption(const char* name, std::string* OUTPUT);
215 
216 // Return true iff the flagname was found. OUTPUT is set to the flag's
217 // CommandLineFlagInfo or unchanged if we return false.
218 extern GFLAGS_DLL_DECL bool GetCommandLineFlagInfo(const char* name,
219                                    CommandLineFlagInfo* OUTPUT);
220 
221 // Return the CommandLineFlagInfo of the flagname.  exit() if name not found.
222 // Example usage, to check if a flag's value is currently the default value:
223 //   if (GetCommandLineFlagInfoOrDie("foo").is_default) ...
224 extern GFLAGS_DLL_DECL CommandLineFlagInfo GetCommandLineFlagInfoOrDie(const char* name);
225 
226 enum GFLAGS_DLL_DECL FlagSettingMode {
227   // update the flag's value (can call this multiple times).
228   SET_FLAGS_VALUE,
229   // update the flag's value, but *only if* it has not yet been updated
230   // with SET_FLAGS_VALUE, SET_FLAG_IF_DEFAULT, or "FLAGS_xxx = nondef".
231   SET_FLAG_IF_DEFAULT,
232   // set the flag's default value to this.  If the flag has not yet updated
233   // yet (via SET_FLAGS_VALUE, SET_FLAG_IF_DEFAULT, or "FLAGS_xxx = nondef")
234   // change the flag's current value to the new default value as well.
235   SET_FLAGS_DEFAULT
236 };
237 
238 // Set a particular flag ("command line option").  Returns a string
239 // describing the new value that the option has been set to.  The
240 // return value API is not well-specified, so basically just depend on
241 // it to be empty if the setting failed for some reason -- the name is
242 // not a valid flag name, or the value is not a valid value -- and
243 // non-empty else.
244 
245 // SetCommandLineOption uses set_mode == SET_FLAGS_VALUE (the common case)
246 extern GFLAGS_DLL_DECL std::string SetCommandLineOption(const char* name, const char* value);
247 extern GFLAGS_DLL_DECL std::string SetCommandLineOptionWithMode(const char* name, const char* value,
248                                            FlagSettingMode set_mode);
249 
250 
251 // --------------------------------------------------------------------
252 // Saves the states (value, default value, whether the user has set
253 // the flag, registered validators, etc) of all flags, and restores
254 // them when the FlagSaver is destroyed.  This is very useful in
255 // tests, say, when you want to let your tests change the flags, but
256 // make sure that they get reverted to the original states when your
257 // test is complete.
258 //
259 // Example usage:
260 //   void TestFoo() {
261 //     FlagSaver s1;
262 //     FLAG_foo = false;
263 //     FLAG_bar = "some value";
264 //
265 //     // test happens here.  You can return at any time
266 //     // without worrying about restoring the FLAG values.
267 //   }
268 //
269 // Note: This class is marked with ATTRIBUTE_UNUSED because all the
270 // work is done in the constructor and destructor, so in the standard
271 // usage example above, the compiler would complain that it's an
272 // unused variable.
273 //
274 // This class is thread-safe.  However, its destructor writes to
275 // exactly the set of flags that have changed value during its
276 // lifetime, so concurrent _direct_ access to those flags
277 // (i.e. FLAGS_foo instead of {Get,Set}CommandLineOption()) is unsafe.
278 
279 class GFLAGS_DLL_DECL FlagSaver {
280  public:
281   FlagSaver();
282   ~FlagSaver();
283 
284  private:
285   class FlagSaverImpl* impl_;   // we use pimpl here to keep API steady
286 
287   FlagSaver(const FlagSaver&);  // no copying!
288   void operator=(const FlagSaver&);
289 }
290 ;
291 
292 // --------------------------------------------------------------------
293 // Some deprecated or hopefully-soon-to-be-deprecated functions.
294 
295 // This is often used for logging.  TODO(csilvers): figure out a better way
296 extern GFLAGS_DLL_DECL std::string CommandlineFlagsIntoString();
297 // Usually where this is used, a FlagSaver should be used instead.
298 extern GFLAGS_DLL_DECL bool ReadFlagsFromString(const std::string& flagfilecontents,
299                                 const char* prog_name,
300                                 bool errors_are_fatal);  // uses SET_FLAGS_VALUE
301 
302 // These let you manually implement --flagfile functionality.
303 // DEPRECATED.
304 extern GFLAGS_DLL_DECL bool AppendFlagsIntoFile(const std::string& filename, const char* prog_name);
305 extern GFLAGS_DLL_DECL bool ReadFromFlagsFile(const std::string& filename, const char* prog_name,
306                               bool errors_are_fatal);   // uses SET_FLAGS_VALUE
307 
308 
309 // --------------------------------------------------------------------
310 // Useful routines for initializing flags from the environment.
311 // In each case, if 'varname' does not exist in the environment
312 // return defval.  If 'varname' does exist but is not valid
313 // (e.g., not a number for an int32 flag), abort with an error.
314 // Otherwise, return the value.  NOTE: for booleans, for true use
315 // 't' or 'T' or 'true' or '1', for false 'f' or 'F' or 'false' or '0'.
316 
317 extern GFLAGS_DLL_DECL bool BoolFromEnv(const char *varname, bool defval);
318 extern GFLAGS_DLL_DECL int32 Int32FromEnv(const char *varname, int32 defval);
319 extern GFLAGS_DLL_DECL int64 Int64FromEnv(const char *varname, int64 defval);
320 extern GFLAGS_DLL_DECL uint64 Uint64FromEnv(const char *varname, uint64 defval);
321 extern GFLAGS_DLL_DECL double DoubleFromEnv(const char *varname, double defval);
322 extern GFLAGS_DLL_DECL const char *StringFromEnv(const char *varname, const char *defval);
323 
324 
325 // --------------------------------------------------------------------
326 // The next two functions parse gflags from main():
327 
328 // Set the "usage" message for this program.  For example:
329 //   string usage("This program does nothing.  Sample usage:\n");
330 //   usage += argv[0] + " <uselessarg1> <uselessarg2>";
331 //   SetUsageMessage(usage);
332 // Do not include commandline flags in the usage: we do that for you!
333 // Thread-hostile; meant to be called before any threads are spawned.
334 extern GFLAGS_DLL_DECL void SetUsageMessage(const std::string& usage);
335 
336 // Sets the version string, which is emitted with --version.
337 // For instance: SetVersionString("1.3");
338 // Thread-hostile; meant to be called before any threads are spawned.
339 extern GFLAGS_DLL_DECL void SetVersionString(const std::string& version);
340 
341 
342 // Looks for flags in argv and parses them.  Rearranges argv to put
343 // flags first, or removes them entirely if remove_flags is true.
344 // If a flag is defined more than once in the command line or flag
345 // file, the last definition is used.  Returns the index (into argv)
346 // of the first non-flag argument.
347 // See top-of-file for more details on this function.
348 #ifndef SWIG   // In swig, use ParseCommandLineFlagsScript() instead.
349 extern GFLAGS_DLL_DECL uint32 ParseCommandLineFlags(int *argc, char*** argv, bool remove_flags);
350 #endif
351 
352 
353 // Calls to ParseCommandLineNonHelpFlags and then to
354 // HandleCommandLineHelpFlags can be used instead of a call to
355 // ParseCommandLineFlags during initialization, in order to allow for
356 // changing default values for some FLAGS (via
357 // e.g. SetCommandLineOptionWithMode calls) between the time of
358 // command line parsing and the time of dumping help information for
359 // the flags as a result of command line parsing.  If a flag is
360 // defined more than once in the command line or flag file, the last
361 // definition is used.  Returns the index (into argv) of the first
362 // non-flag argument.  (If remove_flags is true, will always return 1.)
363 extern GFLAGS_DLL_DECL uint32 ParseCommandLineNonHelpFlags(int *argc, char*** argv,
364                                            bool remove_flags);
365 // This is actually defined in gflags_reporting.cc.
366 // This function is misnamed (it also handles --version, etc.), but
367 // it's too late to change that now. :-(
368 extern GFLAGS_DLL_DECL void HandleCommandLineHelpFlags();   // in gflags_reporting.cc
369 
370 // Allow command line reparsing.  Disables the error normally
371 // generated when an unknown flag is found, since it may be found in a
372 // later parse.  Thread-hostile; meant to be called before any threads
373 // are spawned.
374 extern GFLAGS_DLL_DECL void AllowCommandLineReparsing();
375 
376 // Reparse the flags that have not yet been recognized.  Only flags
377 // registered since the last parse will be recognized.  Any flag value
378 // must be provided as part of the argument using "=", not as a
379 // separate command line argument that follows the flag argument.
380 // Intended for handling flags from dynamically loaded libraries,
381 // since their flags are not registered until they are loaded.
382 extern GFLAGS_DLL_DECL void ReparseCommandLineNonHelpFlags();
383 
384 // Clean up memory allocated by flags.  This is only needed to reduce
385 // the quantity of "potentially leaked" reports emitted by memory
386 // debugging tools such as valgrind.  It is not required for normal
387 // operation, or for the google perftools heap-checker.  It must only
388 // be called when the process is about to exit, and all threads that
389 // might access flags are quiescent.  Referencing flags after this is
390 // called will have unexpected consequences.  This is not safe to run
391 // when multiple threads might be running: the function is
392 // thread-hostile.
393 extern GFLAGS_DLL_DECL void ShutDownCommandLineFlags();
394 
395 
396 // --------------------------------------------------------------------
397 // Now come the command line flag declaration/definition macros that
398 // will actually be used.  They're kind of hairy.  A major reason
399 // for this is initialization: we want people to be able to access
400 // variables in global constructors and have that not crash, even if
401 // their global constructor runs before the global constructor here.
402 // (Obviously, we can't guarantee the flags will have the correct
403 // default value in that case, but at least accessing them is safe.)
404 // The only way to do that is have flags point to a static buffer.
405 // So we make one, using a union to ensure proper alignment, and
406 // then use placement-new to actually set up the flag with the
407 // correct default value.  In the same vein, we have to worry about
408 // flag access in global destructors, so FlagRegisterer has to be
409 // careful never to destroy the flag-values it constructs.
410 //
411 // Note that when we define a flag variable FLAGS_<name>, we also
412 // preemptively define a junk variable, FLAGS_no<name>.  This is to
413 // cause a link-time error if someone tries to define 2 flags with
414 // names like "logging" and "nologging".  We do this because a bool
415 // flag FLAG can be set from the command line to true with a "-FLAG"
416 // argument, and to false with a "-noFLAG" argument, and so this can
417 // potentially avert confusion.
418 //
419 // We also put flags into their own namespace.  It is purposefully
420 // named in an opaque way that people should have trouble typing
421 // directly.  The idea is that DEFINE puts the flag in the weird
422 // namespace, and DECLARE imports the flag from there into the current
423 // namespace.  The net result is to force people to use DECLARE to get
424 // access to a flag, rather than saying "extern bool FLAGS_whatever;"
425 // or some such instead.  We want this so we can put extra
426 // functionality (like sanity-checking) in DECLARE if we want, and
427 // make sure it is picked up everywhere.
428 //
429 // We also put the type of the variable in the namespace, so that
430 // people can't DECLARE_int32 something that they DEFINE_bool'd
431 // elsewhere.
432 
433 class GFLAGS_DLL_DECL FlagRegisterer {
434  public:
435   FlagRegisterer(const char* name, const char* type,
436                  const char* help, const char* filename,
437                  void* current_storage, void* defvalue_storage);
438 };
439 
440 // If your application #defines STRIP_FLAG_HELP to a non-zero value
441 // before #including this file, we remove the help message from the
442 // binary file. This can reduce the size of the resulting binary
443 // somewhat, and may also be useful for security reasons.
444 
445 extern GFLAGS_DLL_DECL const char kStrippedFlagHelp[];
446 
447 }
448 
449 #ifndef SWIG  // In swig, ignore the main flag declarations
450 
451 #if defined(STRIP_FLAG_HELP) && STRIP_FLAG_HELP > 0
452 // Need this construct to avoid the 'defined but not used' warning.
453 #define MAYBE_STRIPPED_HELP(txt) \
454    (false ? (txt) : ::google::kStrippedFlagHelp)
455 #else
456 #define MAYBE_STRIPPED_HELP(txt) txt
457 #endif
458 
459 // Each command-line flag has two variables associated with it: one
460 // with the current value, and one with the default value.  However,
461 // we have a third variable, which is where value is assigned; it's a
462 // constant.  This guarantees that FLAG_##value is initialized at
463 // static initialization time (e.g. before program-start) rather than
464 // than global construction time (which is after program-start but
465 // before main), at least when 'value' is a compile-time constant.  We
466 // use a small trick for the "default value" variable, and call it
467 // FLAGS_no<name>.  This serves the second purpose of assuring a
468 // compile error if someone tries to define a flag named no<name>
469 // which is illegal (--foo and --nofoo both affect the "foo" flag).
470 #define DEFINE_VARIABLE(type, shorttype, name, value, help)             \
471   namespace fL##shorttype {                                             \
472     static const type FLAGS_nono##name = value;                         \
473     /* We always want to export defined variables, dll or no */         \
474     GFLAGS_DLL_DEFINE_FLAG type FLAGS_##name = FLAGS_nono##name;        \
475     type FLAGS_no##name = FLAGS_nono##name;                             \
476     static ::google::FlagRegisterer o_##name( \
477       #name, #type, MAYBE_STRIPPED_HELP(help), __FILE__,                \
478       &FLAGS_##name, &FLAGS_no##name);                                  \
479   }                                                                     \
480   using fL##shorttype::FLAGS_##name
481 
482 // For DEFINE_bool, we want to do the extra check that the passed-in
483 // value is actually a bool, and not a string or something that can be
484 // coerced to a bool.  These declarations (no definition needed!) will
485 // help us do that, and never evaluate From, which is important.
486 // We'll use 'sizeof(IsBool(val))' to distinguish. This code requires
487 // that the compiler have different sizes for bool & double. Since
488 // this is not guaranteed by the standard, we check it with a
489 // COMPILE_ASSERT.
490 namespace fLB {
491 struct CompileAssert {};
492 typedef CompileAssert expected_sizeof_double_neq_sizeof_bool[
493                       (sizeof(double) != sizeof(bool)) ? 1 : -1];
494 template<typename From> double GFLAGS_DLL_DECL IsBoolFlag(const From& from);
495 GFLAGS_DLL_DECL bool IsBoolFlag(bool from);
496 }  // namespace fLB
497 
498 // Here are the actual DEFINE_*-macros. The respective DECLARE_*-macros
499 // are in a separate include, gflags_declare.h, for reducing
500 // the physical transitive size for DECLARE use.
501 #define DEFINE_bool(name, val, txt)                                     \
502   namespace fLB {                                                       \
503     typedef ::fLB::CompileAssert FLAG_##name##_value_is_not_a_bool[     \
504             (sizeof(::fLB::IsBoolFlag(val)) != sizeof(double)) ? 1 : -1]; \
505   }                                                                     \
506   DEFINE_VARIABLE(bool, B, name, val, txt)
507 
508 #define DEFINE_int32(name, val, txt) \
509    DEFINE_VARIABLE(::google::int32, I, \
510                    name, val, txt)
511 
512 #define DEFINE_int64(name, val, txt) \
513    DEFINE_VARIABLE(::google::int64, I64, \
514                    name, val, txt)
515 
516 #define DEFINE_uint64(name,val, txt) \
517    DEFINE_VARIABLE(::google::uint64, U64, \
518                    name, val, txt)
519 
520 #define DEFINE_double(name, val, txt) \
521    DEFINE_VARIABLE(double, D, name, val, txt)
522 
523 // Strings are trickier, because they're not a POD, so we can't
524 // construct them at static-initialization time (instead they get
525 // constructed at global-constructor time, which is much later).  To
526 // try to avoid crashes in that case, we use a char buffer to store
527 // the string, which we can static-initialize, and then placement-new
528 // into it later.  It's not perfect, but the best we can do.
529 
530 namespace fLS {
531 
dont_pass0toDEFINE_string(char * stringspot,const char * value)532 inline clstring* dont_pass0toDEFINE_string(char *stringspot,
533                                            const char *value) {
534   return new(stringspot) clstring(value);
535 }
dont_pass0toDEFINE_string(char * stringspot,const clstring & value)536 inline clstring* dont_pass0toDEFINE_string(char *stringspot,
537                                            const clstring &value) {
538   return new(stringspot) clstring(value);
539 }
540 inline clstring* dont_pass0toDEFINE_string(char *stringspot,
541                                            int value);
542 }  // namespace fLS
543 
544 // We need to define a var named FLAGS_no##name so people don't define
545 // --string and --nostring.  And we need a temporary place to put val
546 // so we don't have to evaluate it twice.  Two great needs that go
547 // great together!
548 // The weird 'using' + 'extern' inside the fLS namespace is to work around
549 // an unknown compiler bug/issue with the gcc 4.2.1 on SUSE 10.  See
550 //    http://code.google.com/p/google-gflags/issues/detail?id=20
551 #define DEFINE_string(name, val, txt)                                       \
552   namespace fLS {                                                           \
553     using ::fLS::clstring;                                                  \
554     static union { void* align; char s[sizeof(clstring)]; } s_##name[2];    \
555     clstring* const FLAGS_no##name = ::fLS::                                \
556                                    dont_pass0toDEFINE_string(s_##name[0].s, \
557                                                              val);          \
558     static ::google::FlagRegisterer o_##name(  \
559         #name, "string", MAYBE_STRIPPED_HELP(txt), __FILE__,                \
560         s_##name[0].s, new (s_##name[1].s) clstring(*FLAGS_no##name));      \
561     extern GFLAGS_DLL_DEFINE_FLAG clstring& FLAGS_##name;                   \
562     using fLS::FLAGS_##name;                                                \
563     clstring& FLAGS_##name = *FLAGS_no##name;                               \
564   }                                                                         \
565   using fLS::FLAGS_##name
566 
567 #endif  // SWIG
568 
569 #endif  // BASE_COMMANDLINEFLAGS_H_
570