Autonomy Software C++ 24.5.1
Welcome to the Autonomy Software repository of the Mars Rover Design Team (MRDT) at Missouri University of Science and Technology (Missouri S&T)! API reference contains the source code and other resources for the development of the autonomy software for our Mars rover. The Autonomy Software project aims to compete in the University Rover Challenge (URC) by demonstrating advanced autonomous capabilities and robust navigation algorithms.
Loading...
Searching...
No Matches
compile_cpp Namespace Reference

Classes

class  Args
class  ANSI

Functions

None print_ansi (str message, *ANSI codes)
None print_if_verbose (str message, *ANSI codes)
None print_separator ()
None print_key_values (str key, list[str] values, int length)
Never print_error_and_exit (str message)
pathlib.Path relative_or_full_path (pathlib.Path path)
tuple[int,...]|None parse_llvm_version (str path_str)
str|None get_llvm_std_module (str search)
pathlib.Path|None find_vs_path ()
list[str] get_module_flags (str name, pathlib.Path module_output_path)
bool compile_module (str name, list[pathlib.Path] paths, pathlib.Path module_output_path)

Variables

 parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
 _ = parser.add_argument("files", action="store", nargs="*", help="the source file(s) to compile")
 args = Args(parser.parse_args(args=None if len(sys.argv) > 1 else ["--help"]))
 ANSI_INFO = ANSI.fg_bright_blue
 ANSI_ERROR = ANSI.fg_bright_red
 ANSI_SUCCESS = ANSI.fg_bright_green
 ANSI_SEPARATOR = ANSI.fg_bright_yellow
 ANSI_TRY_ALL = ANSI.fg_bright_magenta
bool no_color = ""
list source_paths = [pathlib.Path(file) for file in args.files]
list child_args = [arg for arg in sys.argv[1:] if arg not in ("-y", "--try-all")]
list compilers = []
list standards = ["c++17", "c++20", "c++23"]
pathlib workspace_path = pathlib.Path(__file__).parent.parent.resolve()
float compile_start = time.perf_counter()
list warnings_as_errors = "cl" else ["-f-Werror"]
list command
 compile_result
str compiler = ""
pathlib vs_path = find_vs_path()
list defines = args.define[:]
list deps = args.deps[:]
bool disable_exceptions = "true"
list flags = args.flag[:]
list includes = args.include[:]
dict modules = {name: files.split(",") for module in args.module for name, files in (module.split("="),)}
str output = args.output
list pass_args = args.pass_args[:]
str std_module = args.std_module
pathlib compile_yaml = pathlib.Path.cwd() / "compile_cpp.yaml"
dict raw_config = yaml.safe_load(file) or {}
 compile_config = cast("dict[str, Any]", raw_config)
pathlib binary_path = None
pathlib build_folder .Path
bool auto_binary = False
tuple output_path = (pathlib.Path.cwd() / output).resolve()
 exist_ok
 True
 parents
bool use_std_module = not (std_module is None or std_module == "disable" or args.std != "c++23")
str gcc_std_path = "bits/std.cc"
bool success = False
pathlib vc_version_path = vs_path / "VC" / "Auxiliary" / "Build" / "Microsoft.VCToolsVersion.default.txt"
 encoding
str vc_version = vc_version_file.read().strip()
pathlib vc_tools_path = vs_path / "VC" / "Tools" / "MSVC" / vc_version
str clang_path = shutil.which("clang++")
pathlib std_path = pathlib.Path(clang_path).parent.parent / "share" / "libc++" / "v1" / "std.cppm"
str llvm_std_path = get_llvm_std_module("/usr/local/Cellar/llvm")
str module_extension = ""
str short_compiler = "g++" else "msvc"
str suffix = f"{args.type}-{short_compiler}-cpp{args.std[-2:]}"
str extension = "Windows" else ""
str module_indicator = "module_" if args.as_module else ""
str binary_name = f"{source_paths[0].stem}_{module_indicator}{suffix}{extension}"
bool recompiled_modules = False
dict module_paths = {name: [(pathlib.Path.cwd() / file).resolve() for file in files] for name, files in modules.items()}
dict module_output_paths = {name: build_folder / f"{path[0].stem}_module_{suffix}{module_extension}" for name, path in module_paths.items()}
bool need_recompile = True
list deps_paths = [(pathlib.Path.cwd() / file).resolve() for file in deps]
float binary_mod = binary_path.stat().st_mtime
list include_paths = [(pathlib.Path.cwd() / folder).resolve() for folder in includes]
str compiler_path | None
pathlib vs_pwsh_path = vs_path / "Common7" / "Tools" / "Launch-VsDevShell.ps1"
int max_length = 16
float run_start = time.perf_counter()
subprocess run_result

Detailed Description

██████  ███████       ████████ ██   ██ ██████  ███████  █████  ██████          ██████   ██████   ██████  ██
██   ██ ██      ██ ██    ██    ██   ██ ██   ██ ██      ██   ██ ██   ██         ██   ██ ██    ██ ██    ██ ██
██████  ███████          ██    ███████ ██████  █████   ███████ ██   ██         ██████  ██    ██ ██    ██ ██
██   ██      ██ ██ ██    ██    ██   ██ ██   ██ ██      ██   ██ ██   ██         ██      ██    ██ ██    ██ ██
██████  ███████          ██    ██   ██ ██   ██ ███████ ██   ██ ██████  ███████ ██       ██████   ██████  ███████

`BS::thread_pool`: a fast, lightweight, modern, and easy-to-use C++17/C++20/C++23 thread pool library
v5.1.0 (2026-01-03)
By Barak Shoshany <baraksh@gmail.com> <https://baraksh.com/>
Copyright (c) 2021-2026 Barak Shoshany. Licensed under the MIT license. If you found this project useful, please consider starring it on GitHub! If you use this library in software of any kind, please provide a link to the GitHub repository https://github.com/bshoshany/thread-pool in the source code and documentation. If you use this library in published research, please cite it as follows: Barak Shoshany, "A C++17 Thread Pool for High-Performance Scientific Computing", doi:10.1016/j.softx.2024.101687, SoftwareX 26 (2024) 101687, arXiv:2105.00613

This Python script can be used to compile simple C++ programs (with only a few source and/or header files) using a variety of compilers, C++ standards, and other options. It also includes support for C++20 modules and C++23 Standard Library modules. It is used in the thread pool library's development environment to compile and run the test program using different compilers and C++ standards. It is not part of the library itself, but users of the library may find it useful, especially if they wish to use the library as a C++20 module.

Function Documentation

◆ print_ansi()

None compile_cpp.print_ansi ( str message,
*ANSI codes )
Print a message. Uses the given ANSI codes if specified. Does not add newline. Does not print color if the `NO_COLOR` environment variable is set.
140def print_ansi(message: str, *codes: ANSI) -> None:
141 """Print a message. Uses the given ANSI codes if specified. Does not add newline. Does not print color if the `NO_COLOR` environment variable is set."""
142 if len(codes) > 0 and not no_color:
143 seq = ";".join(str(c.value) for c in codes)
144 print(f"\033[{seq}m{message}\033[{ANSI.reset.value}m", end="")
145 else:
146 print(message, end="")
147
148
Here is the caller graph for this function:

◆ print_if_verbose()

None compile_cpp.print_if_verbose ( str message,
*ANSI codes )
Print a message followed by a newline, but only if the verbose flag is set. Uses the given ANSI codes if specified.
149def print_if_verbose(message: str, *codes: ANSI) -> None:
150 """Print a message followed by a newline, but only if the verbose flag is set. Uses the given ANSI codes if specified."""
151 if args.verbose:
152 print_ansi(message + "\n", *codes)
153
154
Here is the call graph for this function:
Here is the caller graph for this function:

◆ print_separator()

None compile_cpp.print_separator ( )
Print a separator line, but only if the verbose flag is set.
155def print_separator() -> None:
156 """Print a separator line, but only if the verbose flag is set."""
157 print_if_verbose("=" * 60, ANSI_SEPARATOR)
158
159
Here is the call graph for this function:
Here is the caller graph for this function:

◆ print_key_values()

None compile_cpp.print_key_values ( str key,
list[str] values,
int length )
Print a key-value pair with the key left-aligned to the given length, but only if the verbose flag is set.
160def print_key_values(key: str, values: list[str], length: int) -> None:
161 """Print a key-value pair with the key left-aligned to the given length, but only if the verbose flag is set."""
162 if args.verbose:
163 print_ansi((key + ":").ljust(length), ANSI.fg_bright_white, ANSI.bold)
164 if len(values) == 0:
165 print("<None>")
166 else:
167 print(values[0])
168 for value in values[1:]:
169 print(" " * length + f"{value}")
170
171
Here is the call graph for this function:
Here is the caller graph for this function:

◆ print_error_and_exit()

Never compile_cpp.print_error_and_exit ( str message)
Print an error message followed by a newline in red and exit.
172def print_error_and_exit(message: str) -> Never:
173 """Print an error message followed by a newline in red and exit."""
174 print_ansi(message + "\n", ANSI_ERROR)
175 sys.exit(1)
176
177
Here is the call graph for this function:
Here is the caller graph for this function:

◆ relative_or_full_path()

pathlib.Path compile_cpp.relative_or_full_path ( pathlib.Path path)
If the path is relative to the current working directory, return it as a relative path; otherwise, return it as a full path.
178def relative_or_full_path(path: pathlib.Path) -> pathlib.Path:
179 """If the path is relative to the current working directory, return it as a relative path; otherwise, return it as a full path."""
180 return path.relative_to(pathlib.Path.cwd()) if path.is_relative_to(pathlib.Path.cwd()) else path
181
182
Here is the caller graph for this function:

◆ parse_llvm_version()

tuple[int, ...] | None compile_cpp.parse_llvm_version ( str path_str)
Extract the LLVM version from a path and returns it as a tuple of integers.
183def parse_llvm_version(path_str: str) -> tuple[int, ...] | None:
184 """Extract the LLVM version from a path and returns it as a tuple of integers."""
185 match: re.Match[str] | None = re.search(r"/llvm[-/](\d+(?:\.\d+)*)", path_str)
186 if match is None:
187 return None
188 return tuple(int(part) for part in match.group(1).split("."))
189
190
Here is the caller graph for this function:

◆ get_llvm_std_module()

str | None compile_cpp.get_llvm_std_module ( str search)
Get the path to the LLVM standard library module on Linux or macOS. If multiple paths are found, return the one with the latest LLVM version.
191def get_llvm_std_module(search: str) -> str | None:
192 """Get the path to the LLVM standard library module on Linux or macOS. If multiple paths are found, return the one with the latest LLVM version."""
193 try:
194 llvm_path: str = subprocess.check_output([f"find {search} -name std.cppm"], text=True, shell=True).strip()
195 except subprocess.CalledProcessError:
196 llvm_path: str = ""
197 all_paths: list[str] = [line for line in llvm_path.splitlines() if line.strip()]
198 if len(all_paths) == 0:
199 return None
200 return max(all_paths, key=lambda p: parse_llvm_version(p) or (0,))
201
202
static softfloat max()
Here is the call graph for this function:
Here is the caller graph for this function:

◆ find_vs_path()

pathlib.Path | None compile_cpp.find_vs_path ( )
Find the Visual Studio installation path, if it exists.
203def find_vs_path() -> pathlib.Path | None:
204 """Find the Visual Studio installation path, if it exists."""
205 if platform.system() != "Windows":
206 return None
207 pf86: str = os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")
208 pf: str = os.environ.get("ProgramFiles", r"C:\Program Files")
209 try_paths: list[pathlib.Path] = [pathlib.Path(p) / "Microsoft Visual Studio" / "Installer" / "vswhere.exe" for p in [pf86, pf]]
210 vswhere: pathlib.Path | None = next((p for p in try_paths if p.exists()), None)
211 if vswhere is None:
212 return None
213 try:
214 install_root: str = subprocess.check_output(
215 [
216 str(vswhere),
217 "-latest",
218 "-property",
219 "installationPath",
220 ],
221 text=True,
222 ).strip()
223 except subprocess.CalledProcessError:
224 return None
225 if install_root == "":
226 return None
227 return pathlib.Path(install_root)
228
229
Here is the caller graph for this function:

◆ get_module_flags()

list[str] compile_cpp.get_module_flags ( str name,
pathlib.Path module_output_path )
Get the appropriate flags to import a module with the given name from the given output path.
230def get_module_flags(name: str, module_output_path: pathlib.Path) -> list[str]:
231 """Get the appropriate flags to import a module with the given name from the given output path."""
232 if compiler == "cl":
233 return ["/reference", f"{name}={module_output_path.resolve()}", *([str(build_folder / f"{module_output_path.stem}.obj")] if (name != "std" or not args.as_module) else [])]
234 if compiler == "clang++":
235 return [f"-fmodule-file={name}={module_output_path.resolve()}"]
236 # Otherwise, compiler == "g++".
237 return ["-fmodules", f"-fmodule-mapper=|@g++-mapper-server -r{build_folder}"]
238
239
Here is the caller graph for this function:

◆ compile_module()

bool compile_cpp.compile_module ( str name,
list[pathlib.Path] paths,
pathlib.Path module_output_path )
Compile a module with the given name. The first path in `paths` is the module file, and the rest are its dependencies. Returns True if the module was recompiled, False if it was up to date.
240def compile_module(name: str, paths: list[pathlib.Path], module_output_path: pathlib.Path) -> bool:
241 """Compile a module with the given name. The first path in `paths` is the module file, and the rest are its dependencies. Returns True if the module was recompiled, False if it was up to date."""
242 module_file: pathlib.Path = paths[0]
243 if module_output_path.exists():
244 module_output_mod: float = module_output_path.stat().st_mtime
245 if not any((path.exists() and path.stat().st_mtime > module_output_mod) for path in paths):
246 print_if_verbose(f'Module "{name}" is up to date, skipping compilation.', ANSI_INFO)
247 return False
248 try:
249 module_command: list[str] = [
250 sys.executable,
251 str(pathlib.Path(__file__).resolve()),
252 # In the special case of GCC and the `std` module, `bits/std.cc` must be entered without the full path.
253 str(module_file) if not (compiler == "g++" and name == "std") else gcc_std_path,
254 f"--output={module_output_path.resolve()}",
255 f"--arch={args.arch}",
256 f"--compiler={compiler}",
257 f"--std={args.std}",
258 f"--type={args.type}",
259 # Note: Not adding the extra options from the configuration file, since they will be added by the script anyway.
260 *[f"--define={define}" for define in args.define],
261 *[f"--include={include}" for include in args.include],
262 *[f"--flag={flag}" for flag in args.flag],
263 # For the `std` module in GCC, we also need to add `-fsearch-include-path`.
264 *(["--flag=-fsearch-include-path"] if (compiler == "g++" and name == "std") else []),
265 # If compiling the `std` module itself, we need to pass `-u=disable` to avoid infinite recursion. Otherwise, we pass along the specified module path if it exists.
266 *(["--std-module=disable"] if name == "std" else [f"--std-module={std_module}"] if std_module is not None else []),
267 "--as-module",
268 *(["--verbose"] if args.verbose else []),
269 *(["--disable-exceptions=true"] if disable_exceptions else ["--disable-exceptions=false"]),
270 ]
271 print_separator()
272 print_if_verbose(f'Compiling module "{name}" with command: {subprocess.list2cmdline(module_command)}', ANSI_INFO)
273 _ = sys.stdout.flush()
274 module_result = subprocess.run(
275 args=module_command,
276 check=False,
277 text=True,
278 )
279 if module_result.returncode != 0:
280 print_error_and_exit(f"Module compilation failed with return code: {module_result.returncode}.")
281 except Exception as exc:
282 print_error_and_exit(f"Could not compile module due to exception: {exc}.")
283 else:
284 return True
285
286
287# Collect the full path(s) to the source file(s).
Here is the call graph for this function:
Here is the caller graph for this function:

Variable Documentation

◆ command

list compile_cpp.command
Initial value:
1= [
2 sys.executable,
3 str(pathlib.Path(__file__).resolve()),
4 "-c",
5 compiler,
6 "-s",
7 std,
8 *warnings_as_errors,
9 *child_args,
10 ]

◆ compile_result

compile_cpp.compile_result
Initial value:
1= subprocess.run(
2 args=command,
3 check=False,
4 text=True,
5 )

◆ run_result

subprocess compile_cpp.run_result
Initial value:
1= subprocess.run(
2 args=[binary_path, *pass_args],
3 check=False,
4 text=True,
5 )