In C/C++, to access a global const char pointer array defined in a header file from another file, you can follow these steps:
- Define the array in a header file (
common.h
) usingextern
keyword to declare it as external:
c// common.h
extern const char *lookup_str[];
- Define the array in a source file (
common.c
) without theextern
keyword:
c// common.c
#include "common.h"
const char *lookup_str[] = {"test Str0", "test Str1", "test Str2", "test Str3"};
- Include the header file in the files where you want to use the array and access it:
c// file1.c
#include "common.h"
#include
int main() {
int ret = 3;
std::string r = lookup_str[ret];
return 0;
}
This way, you can use the lookup_str
array in all your C files by including the common.h
header file. Note that in C++, you should include
for using std::string
.
Also, make sure that common.c
is compiled and linked with other files that use lookup_str
.
المزيد من المعلومات
When working with global const char pointer arrays in C/C++, there are a few things to keep in mind:
-
Initialization: Global variables can be initialized only once. In your case, the initialization
extern const char *lookup_str[] = {"test Str0", "test Str1", "test Str2", "test Str3"};
should be done in a source file (e.g.,common.c
), not in the header file (common.h
). In the header file, declare the array usingextern
. -
Include Guards: Use include guards in your header file to prevent multiple inclusion. For example:
c// common.h #ifndef COMMON_H #define COMMON_H extern const char *lookup_str[]; #endif /* COMMON_H */
-
Accessing the Array: To access the array from another file, include the
common.h
header file at the beginning of the file where you want to use the array:c#include "common.h"
-
File Structure: Make sure your project structure and build system are set up correctly to compile and link all source files together. For example, if you’re using a makefile, ensure that all source files are listed for compilation and linking.
-
C++ String: Since you’re using C++, consider using
std::string
for string manipulation instead of C-style strings. If you’re working in C++, you should include
forstd::string
usage.
Following these guidelines should help you correctly access and use the global const char pointer array in your C/C++ project.