Practical Usage Patterns
Configuration and Initialization
Command-Line Configuration
#include <iostream>
#include <string>
int main(int argc, char* argv[]) {
// LabEx Configuration Handling
std::string mode = "default";
if (argc > 1) {
mode = argv[1];
}
if (mode == "debug") {
std::cout << "Debug mode activated" << std::endl;
} else if (mode == "production") {
std::cout << "Production mode activated" << std::endl;
}
return 0;
}
Error Handling Strategies
graph TD
A[Input Validation] --> B{Valid Input?}
B -->|Yes| C[Process Data]
B -->|No| D[Return Error Code]
D --> E[Exit Program]
Robust Error Reporting
#include <iostream>
#include <fstream>
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " <filename>" << std::endl;
return 1;
}
std::ifstream file(argv[1]);
if (!file.is_open()) {
std::cerr << "Error: Cannot open file " << argv[1] << std::endl;
return 2;
}
// File processing logic
return 0;
}
Exit Code Conventions
Exit Code |
Meaning |
Scenario |
0 |
Success |
Normal execution |
1 |
General error |
Unspecified failure |
2 |
Misuse of shell commands |
Incorrect usage |
126 |
Permission problem |
Cannot execute |
127 |
Command not found |
Invalid command |
Advanced Initialization Patterns
Dependency Injection
class ConfigManager {
public:
static ConfigManager& getInstance(int argc, char* argv[]) {
static ConfigManager instance(argc, argv);
return instance;
}
private:
ConfigManager(int argc, char* argv[]) {
// Initialize with command-line arguments
}
};
int main(int argc, char* argv[]) {
auto& config = ConfigManager::getInstance(argc, argv);
// Use configuration
return 0;
}
Compile and Run on Ubuntu 22.04
## Compile the program
g++ -std=c++11 -o config_demo main.cpp
## Run with different modes
./config_demo debug
./config_demo production
Best Practices for LabEx Developers
- Always validate input
- Use meaningful exit codes
- Provide clear error messages
- Support flexible configuration
- Handle edge cases gracefully
- Minimize initialization overhead
- Use static initialization when possible
- Avoid complex logic in main function
- Delegate responsibilities to appropriate classes
Conclusion
Mastering main()
function patterns enables developers to create robust, flexible, and maintainable C++ applications in the LabEx ecosystem.