1.การตั้งชื่อไฟล์ Header (.h):
- ใช้ตัวพิมพ์เล็กทั้งหมด (lowercase): credentials.h
- กรณีชื่อหลายคำ ใช้ขีดกลาง (kebab-case): wifi-credentials.h
- หรือใช้ขีดล่าง (snake_case): wifi_credentials.h
2.การตั้งชื่อ #define (Header Guard):
// รูปแบบที่นิยมใช้:
#ifndef CREDENTIALS_H
#define CREDENTIALS_H
// ... code ...
#endif
// หรือรูปแบบที่เฉพาะเจาะจงมากขึ้น:
#ifndef WIFI_CREDENTIALS_H
#define WIFI_CREDENTIALS_H
// ... code ...
#endif
กฎการตั้งชื่อ #define:
- ใช้ตัวพิมพ์ใหญ่ทั้งหมด (UPPERCASE)
- ใช้ขีดล่าง (_) คั่นระหว่างคำ
- ลงท้ายด้วย _H เพื่อระบุว่าเป็น header file
- ควรมีความเฉพาะเจาะจงเพื่อป้องกันการชนกันของชื่อ
ตัวอย่างเพิ่มเติมของการตั้งชื่อ #define
#ifndef PROJECT_WIFI_CREDENTIALS_H
#define PROJECT_WIFI_CREDENTIALS_H
// Constants naming convention: UPPERCASE with underscores
const char* WIFI_SSID = "YOUR_WIFI_SSID";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
#endif // PROJECT_WIFI_CREDENTIALS_H
เหตุผลที่ต้องใช้ Header Guard (#ifndef, #define, #endif):
- ป้องกันการ include ไฟล์ซ้ำซ้อน (Multiple Inclusion)
- ป้องกันการเกิด compilation errors
- เป็นมาตรฐานที่ใช้กันทั่วไปใน C/C++
Convention ที่ควรทำ:
// 1. ชื่อไฟล์แบบ snake_case
wifi_credentials.h
// 2. Header guard แบบเฉพาะเจาะจง
#ifndef PROJECT_WIFI_CREDENTIALS_H
#define PROJECT_WIFI_CREDENTIALS_H
// 3. ปิดท้าย #endif ด้วย comment
#endif // PROJECT_WIFI_CREDENTIALS_H
ตัวอย่างการจัดโครงสร้างไฟล์ที่ดี:
#ifndef PROJECT_CONFIG_H
#define PROJECT_CONFIG_H
// WiFi Configuration
#define WIFI_RETRY_DELAY 5000 // 5 seconds
#define WIFI_MAX_ATTEMPTS 10
// MQTT Configuration
#define MQTT_PORT 1883
#define MQTT_KEEPALIVE 60
// Include credentials
#include "wifi_credentials.h"
#endif // PROJECT_CONFIG_H
Best Practices เพิ่มเติม:
- ใช้ชื่อที่มีความหมายและเข้าใจง่าย
- เพิ่ม prefix ของโปรเจ็คเพื่อป้องกันการชนกันของชื่อ
- ใช้ comment อธิบายการปิด #endif
- จัดกลุ่ม constants และ configurations ให้เป็นระเบียบ
- ใช้ case style ให้สอดคล้องกับมาตรฐานของโปรเจ็ค
ตัวอย่างการใช้งานจริง:
#include <Arduino.h>
#include "project_config.h" // รวม configurations ทั้งหมด
#include "wifi_credentials.h" // เฉพาะ credentials
void setup() {
// ใช้ค่าคงที่จาก project_config.h
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < WIFI_MAX_ATTEMPTS) {
delay(WIFI_RETRY_DELAY);
attempts++;
}
}