int output_file_found = 0;
defines output_file_found
.1 Because myshell.h
is included twice, output_file_found
is defined twice, but there should be only one definition of a variable in the entire program. (By nesting blocks inside other blocks, the same name can be used for different variables, so there can be multiple definitions of different variables with the same name. However, both of these declarations appear at file scope, so they attempt to define the same variable.)
In myshell.h
, change the code to extern int output_file_found;
, so that it is only a declaration that is not a definition. In one .c
file in your program, put int output_file_found = 0;
, so there is only one definition.
Do nto include myshell.c
from commands.c
. Source files should only include header files. (The compiler does not much care about the file name suffix, but convention is to use .c
for C source files and .h
for header files.) To use multiple source files in your project, compile them separately into object files, then link the object files together into one program.
It is also common to use “header guards” to prevent the declarations in a header from being processed multiple times by the compiler, in case one header is included multiple times through different paths of nested inclusion by other headers. This will not matter for a variable declaration done correctly, such as extern int output_file_found;
, but it can matter for type definitions and some other declarations. To do this, include these lines at the beginning of the header file:
#if !defined ThisHeaderName_h // Test whether guard has been defined.
#define ThisHeaderName_h // Define guard.
and this line at the end of the header file:
#endif // Matching #if !defined ThisHeaderName_h.
Footnote
1 A declaration with an initialization is a definition. Some other declarations may be definitions too, but the rules are complicated.
extern int output_file_found;
inmyshell.h
and define itint output_file_found = 0
inmyshell.c
(and only inmyshell.c
) – Ted Lyngmo