Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Các file header chuẩn (Standard header files) trong C

Header file (.h) chứa khai báo hàm, macro, kiểu dữ liệu từ thư viện chuẩn. Include bằng #include <header.h>.

Bảng header chuẩn C quan trọng

Ví dụ sử dụng nhiều header

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main() {
    // math.h
    int res = pow(8, 4); // 4096
    printf("math.h: pow(8,4) = %d\n", res);
    
    // stdlib.h
    char s1[] = "53875";
    long a = atol(s1); // 53875
    printf("stdlib.h: atol = %ld\n", a);
    
    // string.h
    char s2[10] = "Hello";
    char s3[10] = "World";
    strcpy(s2, s3);
    printf("string.h: strcpy = %s %s\n", s2, s3);
    
    return 0;
}

Kết quả

math.h: pow(8,4) = 4096
stdlib.h: atol = 53875
string.h: strcpy = World World

C++ Header (C++ Standard Library)

C++ bao gồm header C với tiền tố c và không .h:

HeaderMô tảChính
<stdio.h>Input/Output chuẩnprintf, scanf, fopen, fclose, fgets, fprintf
<stdlib.h>Tiện ích chungmalloc, free, exit, atoi, strtol, rand, qsort, abs
<string.h>Thao tác chuỗi/bytestrcpy, strlen, strcmp, strcat, memset, memcpy
<math.h>Hàm toán họcsin, cos, sqrt, pow, log, exp, floor, ceil
<ctype.h>Phân loại ký tựisalpha, isdigit, isspace, toupper, tolower
<time.h>Ngày giờtime, clock, strftime, localtime, gmtime
<stdint.h>Kiểu int có độ rộng cố định (C99)int32_t, uint64_t, intptr_t, SIZE_MAX
<stdbool.h>Kiểu boolean (C99)bool, true, false
<stddef.h>Kiểu chungsize_t, ptrdiff_t, NULL, offsetof
<limits.h>Giới hạn kiểu sốINT_MAX, CHAR_BIT, LONG_MIN
<float.h>Giới hạn floatFLT_MAX, DBL_EPSILON, DECIMAL_DIG
<errno.h>Mã lỗierrno, EDOM, ERANGE, EILSEQ
<assert.h>Assertion debugassert()
<setjmp.h>Non-local jumpsetjmp, longjmp
<signal.h>Xử lý signalsignal, raise, SIGINT, SIGSEGV
<wchar.h>Wide characterwchar_t, wprintf, wcscpy, wcslen
<wctype.h>Phân loại wide chariswalpha, iswdigit, towupper
<complex.h>Số phức (C99)complex, creal, cimag, cabs
<tgmath.h>Type-generic math (C99)Macro tự chọn float/double/complex
<inttypes.h>Format specifier cho stdintPRId32, PRIu64, SCNx64
C HeaderC++ HeaderNamespace
<stdio.h><cstdio>std::
<stdlib.h><cstdlib>std::
<string.h><cstring>std::
<math.h><cmath>std::
<time.h><ctime>std::

C++ cũng có header riêng: <iostream>, <vector>, <string>, <memory>, <algorithm>, <chrono>...

Best Practice

  • C: #include <header.h>
  • C++: #include <cheader> (trong namespace std) hoặc header C++ native
  • Luôn include header cần thiết (không phụ thuộc transitive include)
  • Sắp xếp: system header trước, project header sau