CPP CPP Interoperability & System Programming 1 — Questions and Answers
Question 1: What is the primary purpose of extern "C" in C++?
- To declare external global variables
- To prevent name mangling so C code can link to C++ functions (Correct answer)
- To include C standard library headers
- To disable C++ exception handling
Correct answer: To prevent name mangling so C code can link to C++ functions
extern "C" instructs the C++ compiler to use C linkage, preventing name mangling so the symbol can be called from C code.
Question 2: Which two techniques are commonly used to prevent multiple inclusions of a header file?
- #once only
- #pragma once only
- #ifndef/#define/#endif only
- Both #pragma once and #ifndef/#define/#endif (Correct answer)
Correct answer: Both #pragma once and #ifndef/#define/#endif
Both the portable #ifndef/#define/#endif include guard pattern and the widely-supported #pragma once compiler extension prevent double inclusion.
Question 3: When calling a C library that allocates memory, how must that memory be freed in C++?
- Use delete
- Use free() (Correct answer)
- Use delete[]
- Use std::destroy
Correct answer: Use free()
Memory allocated by C library functions using malloc/calloc must be released with free(), not delete, to avoid undefined behavior.
Question 4: What does the __cplusplus predefined macro indicate?
- The CPU architecture being targeted
- Whether code is compiled as C++ and which standard version is active (Correct answer)
- The compiler vendor name
- Whether C++ exceptions are enabled
Correct answer: Whether code is compiled as C++ and which standard version is active
The __cplusplus macro is set by C++ compilers to an integer value representing the active standard, such as 201703L for C++17.
Question 5: What is C++ name mangling?
- Renaming variables at runtime for security
- The compiler encoding of a function's full signature into its binary symbol name (Correct answer)
- A technique to obfuscate source code
- Renaming template parameters during instantiation
Correct answer: The compiler encoding of a function's full signature into its binary symbol name
Name mangling encodes the full function signature (including parameter types) into the binary symbol name to support function overloading.
Question 6: How should a C++ function pointer be declared to be safely passed as a callback to a C library?
- As a lambda directly
- As a std::function
- As a free function or static member with extern "C" linkage (Correct answer)
- As a virtual member function
Correct answer: As a free function or static member with extern "C" linkage
C libraries require C-linkage function pointers; a free function or static member declared with extern "C" provides the correct calling convention.
What is the primary purpose of extern "C" in C++?