Compare commits

..

No commits in common. "master" and "v2.1.0" have entirely different histories.

34 changed files with 10305 additions and 21852 deletions

View File

@ -1,19 +0,0 @@
---
Language: Cpp
BasedOnStyle: LLVM
AccessModifierOffset: 0
AlignConsecutiveAssignments: true
AlwaysBreakAfterReturnType: TopLevel
BreakBeforeBraces: Custom
BraceWrapping:
AfterEnum: true
AfterClass: true
AfterStruct: true
AfterFunction: true
AfterNamespace: true
AfterControlStatement: Always
BeforeElse: true
ConstructorInitializerIndentWidth: 2
ContinuationIndentWidth: 2
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left

View File

@ -1,24 +0,0 @@
name: Build cxxopts
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: setup
run: mkdir build
- name: cmake
run: cd build; cmake ..
- name: Build
run: cd build; make -j$(nproc)
- name: test
run: cd build; ctest

View File

@ -1,24 +0,0 @@
name: CIFuzz
on: [pull_request]
jobs:
Fuzzing:
runs-on: ubuntu-latest
steps:
- name: Build Fuzzers
id: build
uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master
with:
oss-fuzz-project-name: 'cxxopts'
language: c++
- name: Run Fuzzers
uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master
with:
oss-fuzz-project-name: 'cxxopts'
language: c++
fuzz-seconds: 300
- name: Upload Crash
uses: actions/upload-artifact@v4
if: failure() && steps.build.outcome == 'success'
with:
name: artifacts
path: ./out/artifacts

View File

@ -1,75 +0,0 @@
name: CMake
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
workflow_dispatch:
env:
# Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.)
BUILD_TYPE: Release
defaults:
run:
shell: bash
jobs:
build-ubuntu:
strategy:
matrix:
os: [ ubuntu-22.04, ubuntu-24.04 ]
compiler: [ g++-9, g++-10, clang++ ]
name: Build and Test on Ubuntu
runs-on: ${{matrix.os}}
steps:
- uses: actions/checkout@v4
- name: Setup g++-9 if not exists
if: matrix.compiler == 'g++-9'
run: which g++-9 || (sudo apt-get update && sudo apt-get -y install g++-9)
- name: Setup g++10 if not exists
if: matrix.compiler == 'g++-10'
run: which g++10 || (sudo apt-get update && sudo apt-get -y install g++-10)
- name: Configure CMake
run: cmake -S "${{github.workspace}}" -B "${{github.workspace}}/build" -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_CXX_COMPILER=${{matrix.compiler}}
- name: Build
run: cmake --build "${{github.workspace}}/build" --config $BUILD_TYPE
- name: Test
working-directory: ${{github.workspace}}/build/test
run: ctest -C $BUILD_TYPE --output-on-failure
build-macos:
name: Build and Test on MacOS
strategy:
matrix:
os: [macos-latest]
runs-on: ${{matrix.os}}
steps:
- uses: actions/checkout@v4
- name: Configure CMake
run: cmake -S "${{github.workspace}}" -B "${{github.workspace}}/build" -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
- name: Show compile commands
run: cat build/compile_commands.json
- name: Build
run: cmake --build "${{github.workspace}}/build" --config $BUILD_TYPE
- name: Test
working-directory: ${{github.workspace}}/build/test
shell: bash
run: ctest -C $BUILD_TYPE --output-on-failure
build-windows:
name: Build and Test on Windows
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- uses: ilammy/msvc-dev-cmd@v1
- name: Configure CMake
run: cmake -S "${{github.workspace}}" -B "${{github.workspace}}/build" -DCMAKE_BUILD_TYPE=$BUILD_TYPE -T "ClangCl"
- name: Build
run: cmake --build "${{github.workspace}}/build" --config $BUILD_TYPE
- name: Test
working-directory: ${{github.workspace}}/build/test
run: cd $BUILD_TYPE && ./link_test && ./options_test

View File

@ -1,59 +0,0 @@
name: Meson
on:
push:
branches: [ master, main ]
pull_request:
branches: [ master, main ]
workflow_dispatch:
jobs:
build-ubuntu:
strategy:
matrix:
icu: [enabled, disabled]
name: Build and Test on Ubuntu
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-python@v5
- uses: BSFishy/meson-build@v1.0.3
with:
action: build
setup-options: -Dicu=${{ matrix.icu }}
meson-version: 0.64.1
directory: builddir
- name: Run Tests
run: meson test -C builddir
- name: Run examples
run: builddir/example
build-macos:
name: Build and Test on MacOS
runs-on: macos-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-python@v5
- uses: BSFishy/meson-build@v1.0.3
with:
action: build
meson-version: 1.10.0
directory: builddir
- name: Run Tests
run: meson test -C builddir
build-windows:
name: Build and Test on Windows
runs-on: windows-latest
steps:
- uses: ilammy/msvc-dev-cmd@v1
- uses: actions/checkout@v6
- uses: actions/setup-python@v5
- uses: BSFishy/meson-build@v1.0.3
with:
action: test
setup-options: -Dcpp_std=c++14 # MSVC doesn't actually support C++11, hide the warning
meson-version: 0.64.1
directory: builddir
- name: Run Tests
run: meson test -C builddir

77
.gitignore vendored
View File

@ -1,77 +1,8 @@
syntax: glob
# Temporary, cache, swap files
\#\#*
*.swp *.swp
*.bkp build*
# Files which "ask" to be hidden
*~
.*
unused/
# Build artifacts
*.a
*.o
*.so
*.ptx
bin/*
lib/*
build/
build-*/
bazel-*
# Core dumps
core
core.*
core-*
# CMake & CTest-generated files
CMakeCache.txt CMakeCache.txt
CMakeFiles/
cmake_install.cmake
CMakeScripts/*
CMakeTmp/*
Makefile Makefile
CTestTestfile.cmake CMakeFiles/
Testing/ Testing/
CTestTestfile.cmake
# Eclise IDE-related files cmake_install.cmake
.project
.cproject
.settings
# CLion IDE-related files
.idea/
cmake-build-*/
# Patching
*.diff
*.rej
*.orig
# Files/folders downloaded from other repositories as part of the build
external/*
third-party/*
# Miscellaneous
tags
log
*.log
*.v3breakpoints
gmon.out
.DS_Store
# Doxygen
doxygen.log
Doxyfile
docs/
# Archives
*.zip
*.gz
*.bz2
*.tgz
*.tar
*.xz

View File

@ -1 +0,0 @@
{ }

View File

@ -1 +0,0 @@

View File

@ -6,35 +6,21 @@ os:
matrix: matrix:
include: include:
- os: linux - os: linux
env: COMPILER=g++-6 env: COMPILER=g++-4.9
addons: addons:
apt: apt:
packages: packages:
- g++-6 - g++-4.9
sources: &sources sources: &sources
- llvm-toolchain-trusty-3.8 - llvm-toolchain-trusty-3.8
- llvm-toolchain-trusty-5.0 - llvm-toolchain-trusty-5.0
- ubuntu-toolchain-r-test - ubuntu-toolchain-r-test
- os: linux - os: linux
env: COMPILER=g++-6 UNICODE_OPTIONS=-DCXXOPTS_USE_UNICODE_HELP=Yes env: COMPILER=g++-4.9 UNICODE_OPTIONS=-DCXXOPTS_USE_UNICODE_HELP=Yes
addons: addons:
apt: apt:
packages: packages:
- g++-6 - g++-4.9
sources: *sources
- os: linux
env: COMPILER=g++-7
addons:
apt:
packages:
- g++-7
sources: *sources
- os: linux
env: COMPILER=g++-7 UNICODE_OPTIONS=-DCXXOPTS_USE_UNICODE_HELP=Yes
addons:
apt:
packages:
- g++-7
sources: *sources sources: *sources
- os: linux - os: linux
env: COMPILER=g++-5 env: COMPILER=g++-5
@ -50,20 +36,6 @@ matrix:
packages: packages:
- g++-5 - g++-5
sources: *sources sources: *sources
- os: linux
env: COMPILER=g++-4.8
addons:
apt:
packages:
- g++-4.8
sources: *sources
- os: linux
env: COMPILER=g++-4.8 UNICODE_OPTIONS=-DCXXOPTS_USE_UNICODE_HELP=Yes
addons:
apt:
packages:
- g++-4.8
sources: *sources
- os: linux - os: linux
env: COMPILER=clang++-3.8 CXXFLAGS=-stdlib=libc++ env: COMPILER=clang++-3.8 CXXFLAGS=-stdlib=libc++
addons: addons:
@ -89,7 +61,7 @@ matrix:
- g++-5 - g++-5
sources: *sources sources: *sources
script: > script: >
cmake -Werror=dev -DCXXOPTS_BUILD_TESTS=ON -DCMAKE_CXX_COMPILER=$COMPILER cmake -DCXXOPTS_BUILD_TESTS=ON -DCMAKE_CXX_COMPILER=$COMPILER
-DCMAKE_CXX_FLAGS=$CXXFLAGS $UNICODE_OPTIONS $CMAKE_OPTIONS . -DCMAKE_CXX_FLAGS=$CXXFLAGS $UNICODE_OPTIONS $CMAKE_OPTIONS .
&& make && make ARGS=--output-on-failure test && make && make ARGS=--output-on-failure test

View File

@ -1,16 +0,0 @@
load("@rules_cc//cc:defs.bzl", "cc_library")
cc_library(
name = "cxxopts",
hdrs = ["include/cxxopts.hpp"],
strip_include_prefix = "include",
visibility = ["//visibility:public"],
)
load("@rules_fuzzing//fuzzing:cc_defs.bzl", "cc_fuzz_test")
cc_fuzz_test(
name = "cxxopts_fuzz_test",
srcs = ["test/fuzz.cpp"],
deps = [":cxxopts"],
)

View File

@ -3,134 +3,6 @@
This is the changelog for `cxxopts`, a C++11 library for parsing command line This is the changelog for `cxxopts`, a C++11 library for parsing command line
options. The project adheres to semantic versioning. options. The project adheres to semantic versioning.
## 3.3.1
### Bug fixes
* Added missing version bump
## 3.3.0
### Bug fixes
* Added missing header for GCC 15
* Fix some CMake packaging problems
### Added
* `as_optional`
* `ParseResult::contains`
* `std::filesystem` support
* CMake 4 compatibility
## 3.2.1
### Bug fixes
* Fix compilation with optional on C++20.
## 3.2
### Bug fixes
* Fix unannotated fallthrough.
* Fix sign conversion with Unicode output.
* Don't initialize regex in static initialiser.
* Fix incorrect integer overflow checks.
### Added
* Add fuzzing to CI
### Changed
* Change quote output to '' to match Windows.
* Don't split positional arguments by the list delimiter.
* Order help groups by the order they were added.
## 3.1.1
### Bug Fixes
* Fixed version number in header.
* Fixed cast warning in Unicode function.
## 3.1
### Added
* Support for multiple long names for the same option (= multiple long aliases)
* Add a `program()` function to retrieve the program name.
* Added a .clang-format file.
* Added iterator and printing for a ParseResult.
### Changed
* Cleanup exception code, add cxxopts::exceptions namespace.
* Renamed several exceptions to be more descriptive, and added to a nested namespace.
### Bug Fixes
* Fix `arguments()` having no key for options that only have a short name.
## 3.0
### Changed
* Only search for a C++ compiler in CMakeLists.txt.
* Allow for exceptions to be disabled.
* Fix duplicate default options when there is a short and long option.
* Add `CXXOPTS_NO_EXCEPTIONS` to disable exceptions.
* Fix char parsing for space and check for length.
* Change argument type in `Options::parse` from `char**` to `const char**`.
* Refactor parser to not change its arguments.
* `ParseResult` doesn't depend on a reference to the parser.
* Fixed several warnings and code quality issues.
* Improved formatting for help descriptions.
* Improve integer parsing.
### Added
* A list of unmatched arguments is available in `ParseResult`.
* Support single letter options with argument attached.
* Use <optional> if it is present.
### Bug Fixes
* Fix missing option name in exception.
## 2.2
### Changed
* Allow integers to have leading zeroes.
* Build the tests by default.
* Don't check for container when showing positional help.
### Added
* Iterator inputs to `parse_positional`.
* Throw an exception if the option in `parse_positional` doesn't exist.
* Parse a delimited list in a single argument for vector options.
* Add an option to disable implicit value on booleans.
### Bug Fixes
* Fix a warning about possible loss of data.
* Fix version numbering in CMakeLists.txt
* Remove unused declaration of the undefined `ParseResult::get_option`.
* Throw on invalid option syntax when beginning with a `-`.
* Throw in `as` when option wasn't present.
* Fix catching exceptions by reference.
* Fix out of bounds errors parsing integers.
## 2.1.1
### Bug Fixes
* Revert the change adding `const` type for `argv`, because most users expect
to pass a non-const `argv` from `main`.
## 2.1 ## 2.1
### Changed ### Changed

View File

@ -17,67 +17,78 @@
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE. # THE SOFTWARE.
cmake_minimum_required(VERSION 3.5...3.19) cmake_minimum_required(VERSION 3.1)
project(cxxopts)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/") enable_testing()
include(cxxopts)
# Get the version of the library set(VERSION "1.2.0")
cxxopts_getversion(VERSION)
project(cxxopts option(CXXOPTS_BUILD_EXAMPLES "Set to ON to build examples" ON)
VERSION "${VERSION}" option(CXXOPTS_BUILD_TESTS "Set to ON to build tests" OFF)
LANGUAGES CXX
)
set("PROJECT_DESCRIPTION" "A header-only lightweight C++ command line option parser") # request c++11 without gnu extension for the whole project and enable more warnings
set("PROJECT_HOMEPAGE_URL" "https://github.com/jarro2783/cxxopts") if (CXXOPTS_CXX_STANDARD)
set(CMAKE_CXX_STANDARD ${CXXOPTS_CXX_STANDARD})
# Must include after the project call due to GNUInstallDirs requiring a language be enabled (IE. CXX) else()
include(GNUInstallDirs) set(CMAKE_CXX_STANDARD 11)
# Determine whether this is a standalone project or included by other projects
set(CXXOPTS_STANDALONE_PROJECT OFF)
if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
set(CXXOPTS_STANDALONE_PROJECT ON)
endif() endif()
# Establish the project options set(CMAKE_CXX_EXTENSIONS OFF)
option(CXXOPTS_BUILD_EXAMPLES "Set to ON to build examples" ${CXXOPTS_STANDALONE_PROJECT})
option(CXXOPTS_BUILD_TESTS "Set to ON to build tests" ${CXXOPTS_STANDALONE_PROJECT})
option(CXXOPTS_ENABLE_INSTALL "Generate the install target" ${CXXOPTS_STANDALONE_PROJECT})
option(CXXOPTS_ENABLE_WARNINGS "Add warnings to CMAKE_CXX_FLAGS" ${CXXOPTS_STANDALONE_PROJECT})
option(CXXOPTS_USE_UNICODE_HELP "Use ICU Unicode library" OFF)
if (CXXOPTS_STANDALONE_PROJECT) if(MSVC)
cxxopts_set_cxx_standard() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W2")
endif() elseif(CMAKE_CXX_COMPILER_ID MATCHES "[Cc]lang" OR CMAKE_CXX_COMPILER_ID MATCHES "GNU")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Werror -Wextra -Wshadow")
if (CXXOPTS_ENABLE_WARNINGS)
cxxopts_enable_warnings()
endif() endif()
add_library(cxxopts INTERFACE) add_library(cxxopts INTERFACE)
add_library(cxxopts::cxxopts ALIAS cxxopts)
add_subdirectory(include)
# Link against the ICU library when requested # optionally, enable unicode support using the ICU library
set(CXXOPTS_USE_UNICODE_HELP FALSE CACHE BOOL "Use ICU Unicode library")
if(CXXOPTS_USE_UNICODE_HELP) if(CXXOPTS_USE_UNICODE_HELP)
cxxopts_use_unicode() find_package(PkgConfig)
pkg_check_modules(ICU REQUIRED icu-uc)
target_link_libraries(cxxopts INTERFACE ${ICU_LDFLAGS})
target_compile_options(cxxopts INTERFACE ${ICU_CFLAGS})
target_compile_definitions(cxxopts INTERFACE CXXOPTS_USE_UNICODE)
endif() endif()
# Install cxxopts when requested by the user target_include_directories(cxxopts INTERFACE
if (CXXOPTS_ENABLE_INSTALL) $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>
cxxopts_install_logic() $<INSTALL_INTERFACE:include>
endif() )
# Build examples when requested by the user include(CMakePackageConfigHelpers)
if (CXXOPTS_BUILD_EXAMPLES) set(CXXOPTS_CMAKE_DIR "lib/cmake/cxxopts" CACHE STRING
add_subdirectory(src) "Installation directory for cmake files, relative to ${CMAKE_INSTALL_PREFIX}.")
endif() set(version_config "${PROJECT_BINARY_DIR}/cxxopts-config-version.cmake")
set(project_config "${PROJECT_BINARY_DIR}/cxxopts-config.cmake")
set(targets_export_name cxxopts-targets)
# Enable testing when requested by the user # Generate the version, config and target files into the build directory.
if (CXXOPTS_BUILD_TESTS) write_basic_package_version_file(
enable_testing() ${version_config}
add_subdirectory(test) VERSION ${VERSION}
endif() COMPATIBILITY AnyNewerVersion)
configure_package_config_file(
${PROJECT_SOURCE_DIR}/cxxopts-config.cmake.in
${project_config}
INSTALL_DESTINATION ${CXXOPTS_CMAKE_DIR})
export(TARGETS cxxopts NAMESPACE cxxopts::
FILE ${PROJECT_BINARY_DIR}/${targets_export_name}.cmake)
# Install version, config and target files.
install(
FILES ${project_config} ${version_config}
DESTINATION ${CXXOPTS_CMAKE_DIR})
install(EXPORT ${targets_export_name} DESTINATION ${CXXOPTS_CMAKE_DIR}
NAMESPACE cxxopts::)
# Install the header file and export the target
install(TARGETS cxxopts EXPORT ${targets_export_name} DESTINATION lib)
install(FILES ${PROJECT_SOURCE_DIR}/include/cxxopts.hpp DESTINATION include)
add_subdirectory(src)
add_subdirectory(test)

46
INSTALL
View File

@ -1,46 +1,10 @@
== System installation == It is preferable to build out of source.
This library is header only. So you can either copy `include/cxxopts.hpp` to `/usr/include` or `/usr/local/include`, or add `include` to your search path. cmake ${CXXOPTS_DIR}
make
== Building the examples and tests ==
It is preferable to build out of source. Make a build directory somewhere, and then
do the following, where `${CXXOPTS_DIR}` is the path that you checked out `cxxopts`
to:
cmake ${CXXOPTS_DIR}
make
You can use another build tool, such as ninja. You can use another build tool, such as ninja.
cmake -G Ninja ${CXXOPTS_DIR} cmake -G Ninja ${CXXOPTS_DIR}
ninja ninja
To run the tests, you have to configure `cxxopts` with another flag:
cmake -D CXXOPTS_BUILD_TESTS=On ${CXXOPTS_DIR}
make
make test
== Using cxxopts in tipi.build projects ==
`cxxopts` can be easily used in [tipi.build](https://tipi.build) projects simply by adding the following entry to your `.tipi/deps`:
```json
{
"jarro2783/cxxopts": { "@": "v3.0.0" }
}
```
To try this you can run the following command in `/src` (change the target name appropriately to `linux` or `macos` or `windows`):
```bash
tipi . -t <target>
./build/linux-cxx17/bin/test_package -v
```
To develop `cxxopts` using tipi run the following command at the root of the repository:
```bash
tipi . -t <target> --test all -v
```

248
README.md
View File

@ -1,41 +1,4 @@
<div align="center"> [![Build Status](https://travis-ci.org/jarro2783/cxxopts.svg?branch=master)](https://travis-ci.org/jarro2783/cxxopts)
[![Build Status](https://img.shields.io/github/actions/workflow/status/jarro2783/cxxopts/cmake.yml?label=build)](https://github.com/jarro2783/cxxopts/actions/workflows/cmake.yml)
[![Conan](https://img.shields.io/conan/v/cxxopts)](https://conan.io/center/recipes/cxxopts)
[![vcpkg](https://img.shields.io/vcpkg/v/cxxopts)](https://vcpkg.io/en/package/cxxopts)
[![GitHub release](https://img.shields.io/github/v/release/jarro2783/cxxopts?label=github%20release)](https://github.com/jarro2783/cxxopts/releases)
[![Header Only](https://img.shields.io/badge/header--only-yes-green.svg)](https://github.com/jarro2783/cxxopts)
[![Mentioned in Awesome C++](https://awesome.re/mentioned-badge.svg)](https://github.com/fffaraz/awesome-cpp)
[![Homebrew](https://img.shields.io/homebrew/installs/dy/cxxopts?label=brew%20downloads&logo=homebrew)](https://formulae.brew.sh/formula/cxxopts)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE)
</div>
# Release versions
Note that `master` is generally a work in progress, and you probably want to use a
tagged release version.
## Version 3 breaking changes
If you have used version 2, there are a couple of breaking changes in version 3
that you should be aware of. If you are new to `cxxopts` you can skip this
section.
The parser no longer modifies its arguments, so you can pass a const `argc` and
`argv` and expect them not to be changed.
The `ParseResult` object no longer depends on the parser. So it can be returned
from a scope outside the parser and still work. Now that the inputs are not
modified, `ParseResult` stores a list of the unmatched arguments. These are
retrieved like follows:
```cpp
auto result = options.parse(argc, argv);
result.unmatched(); // get the unmatched arguments
```
# Quick start # Quick start
@ -57,26 +20,18 @@ Additionally, anything after `--` will be parsed as a positional argument.
## Basics ## Basics
```cpp #include <cxxopts.hpp>
#include <cxxopts.hpp>
```
Create a `cxxopts::Options` instance. Create a cxxopts::Options instance.
```cpp cxxopts::Options options("MyProgram", "One line description of MyProgram");
cxxopts::Options options("MyProgram", "One line description of MyProgram");
```
Then use `add_options`. Then use `add_options`.
```cpp options.add_options()
options.add_options() ("d,debug", "Enable debugging")
("d,debug", "Enable debugging") // a bool parameter
("i,integer", "Int param", cxxopts::value<int>())
("f,file", "File name", cxxopts::value<std::string>()) ("f,file", "File name", cxxopts::value<std::string>())
("v,verbose", "Verbose output", cxxopts::value<bool>()->default_value("false"))
; ;
```
Options are declared with a long and an optional short option. A description Options are declared with a long and an optional short option. A description
must be provided. The third argument is the value, if omitted it is boolean. must be provided. The third argument is the value, if omitted it is boolean.
@ -84,44 +39,26 @@ Any type can be given as long as it can be parsed, with operator>>.
To parse the command line do: To parse the command line do:
```cpp auto result = options.parse(argc, argv);
auto result = options.parse(argc, argv);
```
To retrieve an option use `result.count("option")` to get the number of times To retrieve an option use `result.count("option")` to get the number of times
it appeared, and it appeared, and
```cpp result["opt"].as<type>()
result["opt"].as<type>()
```
to get its value. If "opt" doesn't exist, or isn't of the right type, then an to get its value. If "opt" doesn't exist, or isn't of the right type, then an
exception will be thrown. exception will be thrown.
## Unrecognised arguments Note that the result of `options.parse` should only be used as long as the
`options` object that created it is in scope.
You can allow unrecognised arguments to be skipped. This applies to both
positional arguments that are not parsed into another option, and `--`
arguments that do not match an argument that you specify. This is done by
calling:
```cpp
options.allow_unrecognised_options();
```
and in the result object they are retrieved with:
```cpp
result.unmatched()
```
## Exceptions ## Exceptions
Exceptional situations throw C++ exceptions. There are two types of Exceptional situations throw C++ exceptions. There are two types of
exceptions: errors defining the options, and errors when parsing a list of exceptions: errors defining the options, and errors when parsing a list of
arguments. All exceptions derive from `cxxopts::exceptions::exception`. Errors arguments. All exceptions derive from `cxxopts::OptionException`. Errors
defining options derive from `cxxopts::exceptions::specification` and errors defining options derive from `cxxopts::OptionSpecException` and errors
parsing arguments derive from `cxxopts::exceptions::parsing`. parsing arguments derive from `cxxopts::OptionParseException`.
All exceptions define a `what()` function to get a printable string All exceptions define a `what()` function to get a printable string
explaining the error. explaining the error.
@ -129,46 +66,19 @@ explaining the error.
## Help groups ## Help groups
Options can be placed into groups for the purposes of displaying help messages. Options can be placed into groups for the purposes of displaying help messages.
To place options in a group, pass the group as a string to `add_options`. Then, when displaying the help, `help` by default prints help for all groups. If you want to only print help for a specific group, pass the groups that you would like displayed as a vector to the `help` function. To place options in a group, pass the group as a string to `add_options`. Then,
when displaying the help, pass the groups that you would like displayed as a
vector to the `help` function.
## Positional Arguments ## Positional Arguments
Positional arguments are those given without a preceding flag and can be used Positional arguments can be optionally parsed into one or more options.
alongside non-positional arguments. There may be multiple positional arguments, To set up positional arguments, call
and the final positional argument may be a container type to hold a list of all
remaining positionals.
To set up positional arguments, first declare the options, then configure a options.parse_positional({"first", "second", "last"})
set of those arguments as positional like:
```cpp where "last" should be the name of an option with a container type, and the
options.add_options() others should have a single value.
("script", "The script file to execute", cxxopts::value<std::string>())
("server", "The server to execute on", cxxopts::value<std::string>())
("filenames", "The filename(s) to process", cxxopts::value<std::vector<std::string>>());
options.parse_positional({"script", "server", "filenames"});
// Parse options the usual way
options.parse(argc, argv);
```
Note : `parse_positional` defaults to replacing the positionals with the arguments provided in the function call. To append to the existing list of positionals, please use `cxxopts::PositionalMode::Append`.
```cpp
options.parse_positional("another_option", cxxopts::PositionalMode::Append);
```
For example, parsing the following arguments:
~~~
my_script.py my_server.com file1.txt file2.txt file3.txt
~~~
will result in parsed arguments like the following table:
| Field | Value |
| ------------- | ----------------------------------------- |
| `"script"` | `"my_script.py"` |
| `"server"` | `"my_server.com"` |
| `"filenames"` | `{"file1.txt", "file2.txt", "file3.txt"}` |
## Default and implicit values ## Default and implicit values
@ -177,84 +87,27 @@ An option can be declared with a default or an implicit value, or both.
A default value is the value that an option takes when it is not specified A default value is the value that an option takes when it is not specified
on the command line. The following specifies a default value for an option: on the command line. The following specifies a default value for an option:
```cpp cxxopts::value<std::string>()->default_value("value")
cxxopts::value<std::string>()->default_value("value")
```
An implicit value is the value that an option takes when it is given on the An implicit value is the value that an option takes when it is given on the
command line without an argument. The following specifies an implicit value: command line without an argument. The following specifies an implicit value:
```cpp cxxopts::value<std::string>()->implicit_value("implicit")
cxxopts::value<std::string>()->implicit_value("implicit")
```
If an option had both, then not specifying it would give the value `"value"`, If an option had both, then not specifying it would give the value `"value"`,
writing it on the command line as `--option` would give the value `"implicit"`, writing it on the command line as `--option` would give the value `"implicit"`,
and writing `--option=another` would give it the value `"another"`. and writing `--option=another` would give it the value `"another"`.
Note that if `option` has an implicit value, specifying `--option another` will not work. You must use `=` syntax - `--option=another` or `-o=another`(assumming `o` is a short name for the option). This is because no argument is required. Hence, there is no good way to determine if the next string is an argument to your option or a positional argument.
Note that the default and implicit value is always stored as a string, Note that the default and implicit value is always stored as a string,
regardless of the type that you want to store it in. It will be parsed as regardless of the type that you want to store it in. It will be parsed as
though it was given on the command line. though it was given on the command line.
Default values are not counted by `Options::count`.
### Implicit values with disabled arguments
You can specify an option for which an argument cannot be specified using below syntax.
```cpp
cxxopts::value<bool>()->implicit_value("true", cxxopts::ImplicitArgPolicy::Disabled)
```
In this case specifying option as `--option=<value>` is disallowed and will throw `specified_disabled_args` exception. Note that `--option value` is not supported for implicit values. It is treated as positional/unmatched.
## Boolean values ## Boolean values
Boolean options have a default implicit value of `"true"`, which can be Boolean options have a default implicit value of `"true"`, which can be
overridden. The effect is that writing `-o` by itself will set option `o` to overridden. The effect is that writing `-o` by itself will set option `o` to
`true`. However, they can also be written with various strings using `=value`. `true`. However, they can also be written with various strings using either
There is no way to disambiguate positional arguments from the value following `=value` or the next argument.
a boolean, so we have chosen that they will be positional arguments, and
therefore, `-o false` does not work.
## `std::vector<T>` values
Parsing a list of values into a `std::vector<T>` is also supported, as long as `T`
can be parsed. To separate single values in a list the define symbol `CXXOPTS_VECTOR_DELIMITER`
is used, which is ',' by default. Ensure that you use no whitespaces between values
(unless the entire list is double quoted) because those would be interpreted as the
next command line option. Example for a command line option
that can be parsed as a `std::vector<double>`:
~~~
--my_list=1,-2.1,3,4.5
~~~
If the list of values is quoted, then spaces can be included. For example:
~~~
--my_list="review,memory sanitize,build help,reformat"
~~~
This will be parsed into `review`, `memory sanitize`, `build help`, and `reformat`.
## Options specified multiple times
The same option can be specified several times, with different arguments, which will all
be recorded in order of appearance. An example:
~~~
--use train --use bus --use ferry
~~~
this is supported through the use of a vector of value for the option:
~~~
options.add_options()
("use", "Usable means of transport", cxxopts::value<std::vector<std::string>>())
~~~
## Custom help ## Custom help
@ -262,56 +115,15 @@ The string after the program name on the first line of the help can be
completely replaced by calling `options.custom_help`. Note that you might completely replaced by calling `options.custom_help`. Note that you might
also want to override the positional help by calling `options.positional_help`. also want to override the positional help by calling `options.positional_help`.
## Example
Putting all together:
```cpp
#include <iostream>
#include "cxxopts.hpp"
int main(int argc, char** argv)
{
cxxopts::Options options("test", "A brief description");
options.add_options()
("b,bar", "Param bar", cxxopts::value<std::string>())
("d,debug", "Enable debugging", cxxopts::value<bool>()->default_value("false"))
("f,foo", "Param foo", cxxopts::value<int>()->default_value("10"))
("h,help", "Print usage")
;
auto result = options.parse(argc, argv);
if (result.count("help"))
{
std::cout << options.help() << std::endl;
exit(0);
}
bool debug = result["debug"].as<bool>();
std::string bar;
if (result.count("bar"))
bar = result["bar"].as<std::string>();
int foo = result["foo"].as<int>();
return 0;
}
```
# Linking # Linking
This is a header only library. This is a header only library.
# Requirements # Requirements
The only build requirement is a C++ compiler that supports C++11 features such as: The only build requirement is a C++ compiler that supports C++11 regular
expressions. For example GCC >= 4.9 or clang with libc++.
* regex # TODO list
* constexpr
* default constructors
GCC >= 4.9 or clang >= 3.1 with libc++ are known to work. * Allow unrecognised options.
The following compilers are known not to work:
* MSVC 2013

View File

@ -1,16 +0,0 @@
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "rules_fuzzing",
sha256 = "d9002dd3cd6437017f08593124fdd1b13b3473c7b929ceb0e60d317cb9346118",
strip_prefix = "rules_fuzzing-0.3.2",
urls = ["https://github.com/bazelbuild/rules_fuzzing/archive/v0.3.2.zip"],
)
load("@rules_fuzzing//fuzzing:repositories.bzl", "rules_fuzzing_dependencies")
rules_fuzzing_dependencies()
load("@rules_fuzzing//fuzzing:init.bzl", "rules_fuzzing_init")
rules_fuzzing_init()

View File

@ -1,169 +0,0 @@
# Copyright (c) 2014 Jarryd Beck
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
if (CMAKE_VERSION VERSION_GREATER 3.10 OR CMAKE_VERSION VERSION_EQUAL 3.10)
# Use include_guard() added in cmake 3.10
include_guard()
endif()
include(CMakePackageConfigHelpers)
function(cxxopts_getversion version_arg)
# Parse the current version from the cxxopts header
file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/include/cxxopts.hpp" cxxopts_version_defines
REGEX "#define CXXOPTS__VERSION_(MAJOR|MINOR|PATCH)")
foreach(ver ${cxxopts_version_defines})
if(ver MATCHES "#define CXXOPTS__VERSION_(MAJOR|MINOR|PATCH) +([^ ]+)$")
set(CXXOPTS__VERSION_${CMAKE_MATCH_1} "${CMAKE_MATCH_2}" CACHE INTERNAL "")
endif()
endforeach()
set(VERSION ${CXXOPTS__VERSION_MAJOR}.${CXXOPTS__VERSION_MINOR}.${CXXOPTS__VERSION_PATCH})
# Give feedback to the user. Prefer DEBUG when available since large projects tend to have a lot
# going on already
if (CMAKE_VERSION VERSION_GREATER 3.15 OR CMAKE_VERSION VERSION_EQUAL 3.15)
message(DEBUG "cxxopts version ${VERSION}")
else()
message(STATUS "cxxopts version ${VERSION}")
endif()
# Return the information to the caller
set(${version_arg} ${VERSION} PARENT_SCOPE)
endfunction()
# Optionally, enable unicode support using the ICU library
function(cxxopts_use_unicode)
find_package(PkgConfig)
pkg_check_modules(ICU REQUIRED icu-uc)
target_link_libraries(cxxopts INTERFACE ${ICU_LDFLAGS})
target_compile_options(cxxopts INTERFACE ${ICU_CFLAGS})
target_compile_definitions(cxxopts INTERFACE CXXOPTS_USE_UNICODE)
endfunction()
# Request C++11 without gnu extension for the whole project and enable more warnings
macro(cxxopts_set_cxx_standard)
if (CXXOPTS_CXX_STANDARD)
set(CMAKE_CXX_STANDARD ${CXXOPTS_CXX_STANDARD})
else()
set(CMAKE_CXX_STANDARD 11)
endif()
set(CMAKE_CXX_EXTENSIONS OFF)
endmacro()
# Helper function to enable warnings
function(cxxopts_enable_warnings)
if(MSVC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W2")
elseif(CMAKE_CXX_COMPILER_ID MATCHES "[Cc]lang" OR CMAKE_CXX_COMPILER_ID MATCHES "GNU")
if (CMAKE_CXX_COMPILER_ID MATCHES "GNU")
if (${CMAKE_CXX_COMPILER_VERSION} VERSION_GREATER_EQUAL 5.0)
set(COMPILER_SPECIFIC_FLAGS "-Wsuggest-override")
endif()
endif()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Werror -Wextra -Wshadow -Weffc++ -Wsign-compare -Wshadow -Wwrite-strings -Wpointer-arith -Winit-self -Wconversion -Wno-sign-conversion ${COMPILER_SPECIFIC_FLAGS}")
endif()
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} PARENT_SCOPE)
endfunction()
# Helper function to ecapsulate install logic
function(cxxopts_install_logic)
if(NOT CXXOPTS_USE_UNICODE_HELP)
if(CMAKE_LIBRARY_ARCHITECTURE)
string(REPLACE "/${CMAKE_LIBRARY_ARCHITECTURE}" "" CMAKE_INSTALL_LIBDIR_ARCHIND "${CMAKE_INSTALL_LIBDIR}")
else()
# On some systems (e.g. NixOS), `CMAKE_LIBRARY_ARCHITECTURE` can be empty
set(CMAKE_INSTALL_LIBDIR_ARCHIND "${CMAKE_INSTALL_DATAROOTDIR}")
endif()
if(${CMAKE_VERSION} VERSION_GREATER "3.14")
set(OPTIONAL_ARCH_INDEPENDENT "ARCH_INDEPENDENT")
endif()
else()
set(CMAKE_INSTALL_LIBDIR_ARCHIND "${CMAKE_INSTALL_LIBDIR}")
endif()
set(CXXOPTS_CMAKE_DIR "${CMAKE_INSTALL_LIBDIR_ARCHIND}/cmake/cxxopts" CACHE STRING "Installation directory for cmake files, relative to ${CMAKE_INSTALL_PREFIX}.")
set(version_config "${PROJECT_BINARY_DIR}/cxxopts-config-version.cmake")
set(project_config "${PROJECT_BINARY_DIR}/cxxopts-config.cmake")
set(targets_export_name cxxopts-targets)
set(PackagingTemplatesDir "${PROJECT_SOURCE_DIR}/packaging")
# Generate the version, config and target files into the build directory.
write_basic_package_version_file(
${version_config}
VERSION ${VERSION}
COMPATIBILITY AnyNewerVersion
${OPTIONAL_ARCH_INDEPENDENT}
)
configure_package_config_file(
${PackagingTemplatesDir}/cxxopts-config.cmake.in
${project_config}
INSTALL_DESTINATION ${CXXOPTS_CMAKE_DIR})
export(TARGETS cxxopts NAMESPACE cxxopts::
FILE ${PROJECT_BINARY_DIR}/${targets_export_name}.cmake)
# Install version, config and target files.
install(
FILES ${project_config} ${version_config}
DESTINATION ${CXXOPTS_CMAKE_DIR})
install(EXPORT ${targets_export_name} DESTINATION ${CXXOPTS_CMAKE_DIR}
NAMESPACE cxxopts::)
# Install the header file and export the target
install(TARGETS cxxopts EXPORT ${targets_export_name} DESTINATION ${CMAKE_INSTALL_LIBDIR})
install(FILES ${PROJECT_SOURCE_DIR}/include/cxxopts.hpp DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
set(CPACK_PACKAGE_NAME "${PROJECT_NAME}")
set(CPACK_PACKAGE_VENDOR "cxxopt developers")
set(CPACK_PACKAGE_DESCRIPTION "${PROJECT_DESCRIPTION}")
set(CPACK_DEBIAN_PACKAGE_NAME "${CPACK_PACKAGE_NAME}")
set(CPACK_RPM_PACKAGE_NAME "${CPACK_PACKAGE_NAME}")
set(CPACK_PACKAGE_HOMEPAGE_URL "${PROJECT_HOMEPAGE_URL}")
set(CPACK_PACKAGE_MAINTAINER "${CPACK_PACKAGE_VENDOR}")
set(CPACK_DEBIAN_PACKAGE_MAINTAINER "${CPACK_PACKAGE_MAINTAINER}")
set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE")
set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md")
set(CPACK_DEBIAN_PACKAGE_NAME "lib${PROJECT_NAME}-dev")
set(CPACK_DEBIAN_PACKAGE_DEPENDS "libc6-dev")
set(CPACK_DEBIAN_PACKAGE_SUGGESTS "cmake, pkg-config, pkg-conf")
set(CPACK_RPM_PACKAGE_NAME "lib${PROJECT_NAME}-devel")
set(CPACK_RPM_PACKAGE_SUGGESTS "${CPACK_DEBIAN_PACKAGE_SUGGESTS}")
set(CPACK_DEB_COMPONENT_INSTALL ON)
set(CPACK_RPM_COMPONENT_INSTALL ON)
set(CPACK_NSIS_COMPONENT_INSTALL ON)
set(CPACK_DEBIAN_COMPRESSION_TYPE "xz")
set(PKG_CONFIG_FILE_NAME "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.pc")
if(CXXOPTS_USE_UNICODE_HELP)
set(PKG_CONFIG_REQUIRES "icu-uc")
set(PKG_CONFIG_EXTRA_CFLAGS "-DCXXOPTS_USE_UNICODE")
endif()
configure_file("${PackagingTemplatesDir}/pkgconfig.pc.in" "${PKG_CONFIG_FILE_NAME}" @ONLY)
install(FILES "${PKG_CONFIG_FILE_NAME}"
DESTINATION "${CMAKE_INSTALL_LIBDIR_ARCHIND}/pkgconfig"
)
include(CPack)
endfunction()

View File

@ -1,23 +0,0 @@
# Copyright (c) 2014 Jarryd Beck
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
target_include_directories(cxxopts INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>
$<INSTALL_INTERFACE:include>
)

File diff suppressed because it is too large Load Diff

View File

@ -1,97 +0,0 @@
# Copyright © 2024-2026 Dylan Baker
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
project(
'cxxopts',
'cpp',
version : run_command(
'meson/version.py', files('include/cxxopts.hpp'), capture : true, check : true).stdout().strip(),
meson_version : '>= 0.64',
license : 'MIT',
default_options : ['cpp_std=c++11', 'warning_level=2'],
)
cpp = meson.get_compiler('cpp')
with_warnings = get_option('warnings').disable_auto_if(meson.is_subproject()).allowed()
if with_warnings
add_project_arguments(
cpp.get_supported_arguments(
'-Wsuggest-override',
'-Wshadow',
'-Weffc++',
'-Wsign-compare',
'-Wshadow',
'-Wwrite-strings',
'-Wpointer-arith',
'-Winit-self',
'-Wconversion',
'-Wno-sign-conversion',
),
language : 'cpp',
)
endif
install_headers('include/cxxopts.hpp')
dep_icu = dependency('icu-uc', required : get_option('icu'))
if dep_icu.found()
add_project_arguments('-DCXXOPTS_USE_UNICODE', language : 'cpp')
endif
with_examples = get_option('examples').disable_auto_if(meson.is_subproject()).allowed()
if with_examples
executable(
'example',
'src/example.cpp',
include_directories : 'include',
dependencies : dep_icu,
override_options : ['cpp_std=c++17'],
)
endif
with_tests = get_option('tests').disable_auto_if(meson.is_subproject()).allowed()
if with_tests
subdir('test')
endif
extra_cflags = []
if dep_icu.found()
extra_cflags += ['-DCXXOPTS_USE_UNICODE']
endif
dep_cxxopts = declare_dependency(
include_directories : 'include',
dependencies : dep_icu,
compile_args : extra_cflags,
)
meson.override_dependency('cxxopts', dep_cxxopts)
pkg = import('pkgconfig')
pkg.generate(
name : 'cxxopts',
description : 'A header-only lightweight C++ command line option parser',
url : 'https://github.com/jarro2783/cxxopts',
extra_cflags : extra_cflags,
requires : dep_icu,
dataonly : not dep_icu.found(),
)

View File

@ -1,47 +0,0 @@
#!/usr/bin/env python
# Copyright © 2024-2026 Dylan Baker
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Parse the cxxopts.hpp header to get the version."""
import sys
def main():
versions = [None, None, None]
with open(sys.argv[1], 'r', encoding='ascii') as f:
for line in f:
if line.startswith('#define CXXOPTS__VERSION_'):
ver = line.rstrip().rsplit(' ', 1)[-1]
if 'MAJOR' in line:
versions[0] = ver
elif 'MINOR' in line:
versions[1] = ver
elif 'PATCH' in line:
versions[2] = ver
if None not in versions:
break
assert None not in versions, \
"Did not find all of the expected version strings in cxxopts.hpp"
print('.'.join(versions))
if __name__ == "__main__":
main()

View File

@ -1,41 +0,0 @@
# Copyright © 2024-2026 Dylan Baker
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
option(
'examples',
type : 'feature',
description : 'Whether to build examples. Defaults to enabled when not built as a subproject, otherwise disabled.',
)
option(
'tests',
type : 'feature',
description : 'Whether to build tests. Defaults to enabled when not built as a subproject, otherwise disabled.',
)
option(
'warnings',
type : 'feature',
description : 'Whether to add additional warnings. Defaults to enabled when not built as a subproject, otherwise disabled.',
)
option(
'icu',
type : 'feature',
value : 'disabled',
description : 'use ICU Unicode library.',
)

View File

@ -1,9 +0,0 @@
prefix=@CMAKE_INSTALL_PREFIX@
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
Name: @PROJECT_NAME@
Description: @PROJECT_DESCRIPTION@
URL: @PROJECT_HOMEPAGE_URL@
Version: @PROJECT_VERSION@
Requires: @PKG_CONFIG_REQUIRES@
Cflags: -I${includedir} @PKG_CONFIG_EXTRA_CFLAGS@

View File

@ -1,3 +0,0 @@
{
"jarro2783/cxxopts": { }
}

View File

@ -18,9 +18,7 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE. # THE SOFTWARE.
add_executable(example example.cpp) if(CXXOPTS_BUILD_EXAMPLES)
target_link_libraries(example cxxopts) add_executable(example example.cpp)
target_link_libraries(example cxxopts)
target_compile_features(example PRIVATE cxx_std_17) endif()
target_compile_options(example PRIVATE
"$<$<CXX_COMPILER_ID:MSVC>:/utf-8;>")

View File

@ -21,51 +21,39 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*/ */
#include "cxxopts.hpp"
#include <iostream> #include <iostream>
#include <memory>
int #include "cxxopts.hpp"
parse(int argc, const char* argv[])
int main(int argc, const char* argv[])
{ {
try try
{ {
std::unique_ptr<cxxopts::Options> allocated(new cxxopts::Options(argv[0], " - example command line options")); cxxopts::Options options(argv[0], " - example command line options");
auto& options = *allocated;
options options
.positional_help("[optional args]") .positional_help("[optional args]")
.show_positional_help(); .show_positional_help();
bool apple = false; bool apple = false;
options options.add_options()
.set_width(70) ("a,apple", "an apple", cxxopts::value<bool>(apple))
.set_tab_expansion()
.allow_unrecognised_options()
.add_options()
("a,apple,ringo", "an apple", cxxopts::value<bool>(apple))
("b,bob", "Bob") ("b,bob", "Bob")
("char", "A character", cxxopts::value<char>())
("t,true", "True", cxxopts::value<bool>()->default_value("true")) ("t,true", "True", cxxopts::value<bool>()->default_value("true"))
("f, file", "File", cxxopts::value<std::vector<std::string>>(), "FILE") ("f, file", "File", cxxopts::value<std::vector<std::string>>(), "FILE")
("i,input", "Input", cxxopts::value<std::string>()) ("i,input", "Input", cxxopts::value<std::string>())
("o,output", "Output file", cxxopts::value<std::string>() ("o,output", "Output file", cxxopts::value<std::string>()
->default_value("a.out")->implicit_value("b.def"), "BIN") ->default_value("a.out")->implicit_value("b.def"), "BIN")
("x", "A short-only option", cxxopts::value<std::string>())
("positional", ("positional",
"Positional arguments: these are the arguments that are entered " "Positional arguments: these are the arguments that are entered "
"without an option", cxxopts::value<std::vector<std::string>>()) "without an option", cxxopts::value<std::vector<std::string>>())
("long-description", ("long-description",
"thisisareallylongwordthattakesupthewholelineandcannotbebrokenataspace") "thisisareallylongwordthattakesupthewholelineandcannotbebrokenataspace")
("help", "Print help") ("help", "Print help")
("tab-expansion", "Tab\texpansion")
("int", "An integer", cxxopts::value<int>(), "N") ("int", "An integer", cxxopts::value<int>(), "N")
("float", "A floating point number", cxxopts::value<float>()) ("float", "A floating point number", cxxopts::value<float>())
("vector", "A list of doubles", cxxopts::value<std::vector<double>>())
("option_that_is_too_long_for_the_help", "A very long option") ("option_that_is_too_long_for_the_help", "A very long option")
("l,list", "List all parsed arguments (including default values)")
("range", "Use range-for to list arguments")
#ifdef CXXOPTS_USE_UNICODE #ifdef CXXOPTS_USE_UNICODE
("unicode", u8"A help option with non-ascii: à. Here the size of the" ("unicode", u8"A help option with non-ascii: à. Here the size of the"
" string should be correct") " string should be correct")
@ -83,23 +71,7 @@ parse(int argc, const char* argv[])
if (result.count("help")) if (result.count("help"))
{ {
std::cout << options.help({"", "Group"}) << std::endl; std::cout << options.help({"", "Group"}) << std::endl;
return true; exit(0);
}
if(result.count("list"))
{
if(result.count("range"))
{
for(const auto &kv: result)
{
std::cout << kv.key() << " = " << kv.value() << std::endl;
}
}
else
{
std::cout << result.arguments_string() << std::endl;
}
return true;
} }
if (apple) if (apple)
@ -113,11 +85,6 @@ parse(int argc, const char* argv[])
std::cout << "Saw option b" << std::endl; std::cout << "Saw option b" << std::endl;
} }
if (result.count("char"))
{
std::cout << "Saw a character " << result["char"].as<char>() << "" << std::endl;
}
if (result.count("f")) if (result.count("f"))
{ {
auto& ff = result["f"].as<std::vector<std::string>>(); auto& ff = result["f"].as<std::vector<std::string>>();
@ -160,42 +127,12 @@ parse(int argc, const char* argv[])
std::cout << "float = " << result["float"].as<float>() << std::endl; std::cout << "float = " << result["float"].as<float>() << std::endl;
} }
if (result.count("vector"))
{
std::cout << "vector = ";
const auto values = result["vector"].as<std::vector<double>>();
for (const auto& v : values) {
std::cout << v << ", ";
}
std::cout << std::endl;
}
std::cout << "Arguments remain = " << argc << std::endl; std::cout << "Arguments remain = " << argc << std::endl;
auto arguments = result.arguments(); } catch (const cxxopts::OptionException& e)
std::cout << "Saw " << arguments.size() << " arguments" << std::endl;
std::cout << "Unmatched options: ";
for (const auto& option: result.unmatched())
{
std::cout << "'" << option << "' ";
}
std::cout << std::endl;
}
catch (const cxxopts::exceptions::exception& e)
{ {
std::cout << "error parsing options: " << e.what() << std::endl; std::cout << "error parsing options: " << e.what() << std::endl;
return false; exit(1);
}
return true;
}
int main(int argc, const char* argv[])
{
if (!parse(argc, argv))
{
return 1;
} }
return 0; return 0;

View File

@ -1,2 +0,0 @@
link_a.cpp
link_b.cpp

View File

@ -1,43 +1,10 @@
# Copyright (c) 2014 Jarryd Beck if (CXXOPTS_BUILD_TESTS)
# add_executable(options_test main.cpp options.cpp)
# Permission is hereby granted, free of charge, to any person obtaining a copy target_link_libraries(options_test cxxopts)
# of this software and associated documentation files (the "Software"), to deal add_test(options options_test)
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
add_executable(options_test main.cpp options.cpp) # test if the targets are findable from the build directory
target_link_libraries(options_test cxxopts) add_test(find-package-test ${CMAKE_CTEST_COMMAND}
add_test(options options_test)
add_executable(options_test_noregex main.cpp options.cpp)
target_link_libraries(options_test_noregex cxxopts)
target_compile_definitions(options_test_noregex PRIVATE CXXOPTS_NO_REGEX)
add_test(options_no_regex options_test_noregex)
# Run the parser tests under UBSan so undefined behaviour in integer parsing
# (e.g. std::abs(INT64_MIN)) fails the build instead of going unnoticed.
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU" AND NOT WIN32)
foreach(test_target options_test options_test_noregex)
target_compile_options(${test_target} PRIVATE -fsanitize=undefined -fno-sanitize-recover=undefined)
set_target_properties(${test_target} PROPERTIES LINK_FLAGS "-fsanitize=undefined -fno-sanitize-recover=undefined")
endforeach()
endif()
# test if the targets are findable from the build directory
add_test(find-package-test ${CMAKE_CTEST_COMMAND}
-C ${CMAKE_BUILD_TYPE} -C ${CMAKE_BUILD_TYPE}
--build-and-test --build-and-test
"${CMAKE_CURRENT_SOURCE_DIR}/find-package-test" "${CMAKE_CURRENT_SOURCE_DIR}/find-package-test"
@ -46,14 +13,12 @@ add_test(find-package-test ${CMAKE_CTEST_COMMAND}
--build-makeprogram ${CMAKE_MAKE_PROGRAM} --build-makeprogram ${CMAKE_MAKE_PROGRAM}
--build-options --build-options
"-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}" "-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}"
"-DCMAKE_CXX_STANDARD=${CMAKE_CXX_STANDARD}"
"-DCMAKE_CXX_EXTENSIONS=${CMAKE_CXX_EXTENSIONS}"
"-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}" "-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}"
"-Dcxxopts_DIR=${PROJECT_BINARY_DIR}" "-Dcxxopts_DIR=${PROJECT_BINARY_DIR}"
) )
# test if the targets are findable when add_subdirectory is used # test if the targets are findable when add_subdirectory is used
add_test(add-subdirectory-test ${CMAKE_CTEST_COMMAND} add_test(add-subdirectory-test ${CMAKE_CTEST_COMMAND}
-C ${CMAKE_BUILD_TYPE} -C ${CMAKE_BUILD_TYPE}
--build-and-test --build-and-test
"${CMAKE_CURRENT_SOURCE_DIR}/add-subdirectory-test" "${CMAKE_CURRENT_SOURCE_DIR}/add-subdirectory-test"
@ -62,17 +27,9 @@ add_test(add-subdirectory-test ${CMAKE_CTEST_COMMAND}
--build-makeprogram ${CMAKE_MAKE_PROGRAM} --build-makeprogram ${CMAKE_MAKE_PROGRAM}
--build-options --build-options
"-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}" "-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}"
"-DCMAKE_CXX_STANDARD=${CMAKE_CXX_STANDARD}"
"-DCMAKE_CXX_EXTENSIONS=${CMAKE_CXX_EXTENSIONS}"
"-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}" "-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}"
) )
add_executable(link_test link_a.cpp link_b.cpp) add_executable(link_test link_a.cpp link_b.cpp)
target_link_libraries(link_test cxxopts) target_link_libraries(link_test cxxopts)
if(("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") AND ("${CMAKE_SYSTEM}" MATCHES "Linux"))
add_executable(fuzzer fuzz.cpp)
target_link_libraries(fuzzer PRIVATE cxxopts)
target_compile_options(fuzzer PRIVATE -fsanitize=fuzzer)
target_link_options(fuzzer PRIVATE -fsanitize=fuzzer)
endif() endif()

View File

@ -1,7 +1,10 @@
cmake_minimum_required(VERSION 3.5...3.19) cmake_minimum_required(VERSION 3.1)
project(cxxopts-test) project(cxxopts-test)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_EXTENSIONS OFF)
add_subdirectory(../.. cxxopts EXCLUDE_FROM_ALL) add_subdirectory(../.. cxxopts EXCLUDE_FROM_ALL)
add_executable(library-test "../../src/example.cpp") add_executable(library-test "../../src/example.cpp")

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,10 @@
cmake_minimum_required(VERSION 3.5...3.19) cmake_minimum_required(VERSION 3.1)
project(cxxopts-test) project(cxxopts-test)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_EXTENSIONS OFF)
find_package(cxxopts REQUIRED) find_package(cxxopts REQUIRED)
add_executable(library-test "../../src/example.cpp") add_executable(library-test "../../src/example.cpp")

View File

@ -1,107 +0,0 @@
#include <cassert>
#include <cxxopts.hpp>
#include <fuzzer/FuzzedDataProvider.h>
constexpr int kMaxOptions = 1024;
constexpr int kMaxArgSize = 1024;
enum class ParseableTypes
{
kInt,
kString,
kVectorString,
kFloat,
kDouble,
// Marker for fuzzer.
kMaxValue,
};
template <typename T>
void
add_fuzzed_option(cxxopts::Options* options, FuzzedDataProvider* provider)
{
assert(options);
assert(provider);
options->add_options()(provider->ConsumeRandomLengthString(kMaxArgSize),
provider->ConsumeRandomLengthString(kMaxArgSize),
cxxopts::value<T>());
}
extern "C" int
LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
try
{
FuzzedDataProvider provider(data, size);
// Randomly generate a usage string.
cxxopts::Options options(provider.ConsumeRandomLengthString(kMaxArgSize),
provider.ConsumeRandomLengthString(kMaxArgSize));
// Randomly generate a set of flags configurations.
for (int i = 0; i < provider.ConsumeIntegralInRange<int>(0, kMaxOptions);
i++)
{
switch (provider.ConsumeEnum<ParseableTypes>())
{
case ParseableTypes::kInt:
add_fuzzed_option<int>(&options, &provider);
break;
case ParseableTypes::kString:
add_fuzzed_option<std::string>(&options, &provider);
break;
case ParseableTypes::kVectorString:
add_fuzzed_option<std::vector<std::string>>(&options, &provider);
break;
case ParseableTypes::kFloat:
add_fuzzed_option<float>(&options, &provider);
break;
case ParseableTypes::kDouble:
add_fuzzed_option<double>(&options, &provider);
break;
default:
break;
}
}
// Sometimes allow unrecognised options.
if (provider.ConsumeBool())
{
options.allow_unrecognised_options();
}
// Sometimes allow trailing positional arguments.
if (provider.ConsumeBool())
{
std::string positional_option_name =
provider.ConsumeRandomLengthString(kMaxArgSize);
options.add_options()(positional_option_name,
provider.ConsumeRandomLengthString(kMaxArgSize),
cxxopts::value<std::vector<std::string>>());
options.parse_positional({positional_option_name});
}
// Build command line input.
const int argc = provider.ConsumeIntegralInRange<int>(1, kMaxOptions);
std::vector<std::string> command_line_container;
command_line_container.reserve(argc);
std::vector<const char*> argv;
argv.reserve(argc);
for (int i = 0; i < argc; i++)
{
command_line_container.push_back(
provider.ConsumeRandomLengthString(kMaxArgSize));
argv.push_back(command_line_container[i].c_str());
}
// Parse command line;
auto result = options.parse(argc, argv.data());
} catch (...)
{
}
return 0;
}

View File

@ -1,55 +0,0 @@
# Copyright © 2024-2026 Dylan Baker
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
inc = include_directories('../include')
test(
'link',
executable(
'link_test',
'link_a.cpp', 'link_b.cpp',
dependencies : dep_icu,
include_directories : inc,
)
)
test(
'options',
executable(
'options_test',
'main.cpp', 'options.cpp',
dependencies : dep_icu,
include_directories : inc,
)
)
if cpp.get_id() == 'clang' and host_machine.system() == 'linux'
executable(
'fuzzer',
'fuzz.cpp',
cpp_args : ['-fsanitize=fuzzer'],
link_args : ['-fsanitize=fuzzer'],
dependencies : dep_icu,
include_directories : inc,
)
endif
# Meson can generate basic cmake-configs files, but not when targets are used,
# so these tests don't make sense

File diff suppressed because it is too large Load Diff