C API for Windows to handle command line parameters with short and long options
-
Install Visual Studio (e.g. Community) choosing the following
single components:MSVC v142+ - C++ Build toolsC++/CLI for Build Tools v142+Windows 11 SDKCMake C++ Tools for Windows
-
Download the repository
-
Add the following environmental variable as User:
VS_DIR: Path to Visual Studio with all folders (e.g.Microsoft Visual Studio\2022\Community)
-
Run the following in a
Command Prompt(no PowerShell) to install it:"%VS_DIR%\VC\Auxiliary\Build\vcvarsall.bat" x64_x86 cd c-cmd-api cmake -B build -S . -L -DCMAKE_INSTALL_PREFIX=<install_folder> cmake --build build --target install --config ReleaseNote: Generate shared libraries (
.lib+.dll) instead as follows:cmake -B build -S . -L -DCMAKE_INSTALL_PREFIX=<install_folder> -DSHARED=ON -
When using the library in your project make sure to:
- Include
<install_folder>/include - Link the library
<install_folder>/lib/cmd-api.lib
- Include
In your CMakeLists.txt file
...
find_package(cmd-api PATHS "<install_folder>" REQUIRED)
include_directories(${cmd-api_INCLUDE_DIR})
add_executable(${PROJECT_NAME} yourmain.cpp)
target_link_libraries(${PROJECT_NAME} "${cmd-api_LIBRARIES}")
install(FILES ${cmd-api_RUNTIME} DESTINATION bin)
install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION bin)
install(TARGETS ${PROJECT_NAME} LIBRARY DESTINATION lib)
...
#include "cmd-api.h"
int main(int argc, char* argv[]) {
optarg_t* optarg;
while ((optarg = getoptW(argc, argv, "o:|opt1:|opt2:|")) != NULL)
{
if (strcmp(optarg->opt, "o") == 0) {
/*use optarg->arg that has the argument of o*/
continue;
}
if (strcmp(optarg->opt, "opt1") == 0) {
/*use optarg->arg that has the argument of opt1*/
continue;
}
if (strcmp(optarg->opt, "opt2") == 0) {
/*use optarg->arg that has the argument of opt2*/
continue;
}
free(optarg);
}
...
}
cmake -B build -S . -L -DCMAKE_INSTALL_PREFIX=<install_folder>
cmake --build .\build --target install --config Release
cd build
ctest --build-config Release --build-target install