The short answer
#include <string.h> brings the declarations of C’s string-handling functions into your program. These include strlen, strcpy, strcat and strcmp. The header is part of the standard C library, so you do not need to install anything extra for it.
What #include does
#include is a preprocessor directive. Before the compiler reads the file, the preprocessor replaces the #include line with the contents of the named header. The header declares the functions, so the compiler knows their names and the arguments they take.
Angle brackets, as in <string.h>, tell the preprocessor to look in the system’s standard include locations. Quotes, as in "myfile.h", usually make it look in the folder with your source file first.
Functions declared in string.h
Some of the functions it declares are:
strlenreturns the length of a string, not counting the null character.strcpycopies a string into a buffer. The buffer must be big enough to hold it.strcatappends one string to another. The first string must have room for both. It is covered in how to concatenate strings in c.strcmpcompares two strings. It returns 0 when they match.strstrfinds a substring. For details, read What does strstr() do in C?memcpyandmemsetwork on raw memory rather than null-terminated strings.
Example program
#include <stdio.h>
#include <string.h>
int main(void) {
char first[20] = "Hello, ";
char second[] = "world";
strcat(first, second);
printf("%s\n", first);
printf("Length: %zu\n", strlen(first));
return 0;
}
Output:
Hello, world
Length: 12
first has room for 20 characters, including the null. “Hello, world” needs 12 characters plus the null, so the buffer is large enough. The <stdio.h> header provides printf, and <string.h> provides strcat and strlen.
What happens without the include
If a file calls strlen without including <string.h>, the compiler does not know what strlen is. Depending on the compiler and its settings, it may print a warning about an implicit declaration or stop with an error. Include the header at the top of any file that uses these functions. A header is an ordinary text file, as explained in What is a .h file?
The C++ version
C++ programs can use the same functions through <cstring>, which declares them in the std namespace. <string.h> still works in C++, but <cstring> is the usual choice in C++ code.
#include <string> is different. It provides the std::string class, not the C functions.
Summary
#include <string.h>loads the declarations for C’s string functions.- The preprocessor copies the header into your file before compiling.
- Include it in any file that calls these functions.
- In C++, use
<cstring>for the C functions and<string>forstd::string.