I have a function that is used by a number of my sketches. I would like to put the structure definitions and the function into #include files and then replace the copies that are in my sketches with #include statements. For reference, I am using Arduino IDE 1.8.13 on Windows 10.
To that end, I created a created a directory called ..\mySketches\library\comhdr and put a file in this directory that is called comhdr.h. It contains the structure definitions. In a sketch I replaced the structure definition with the statement #include “comhdr.h”. I then compiled the sketch and it completed without error.
I attemtpted the same procedure with the function: I created a directory ..\mySketches\library\comfunc and put a file in this directory that is called comfunc.c. It contains the function. In the sketch I replaced the function with the statement #include “comfunc.c”. I then compiled the sketch. The compile fails, saying that the file comfunc.c cannot be found.
I then changed the include to #include “comfunc.h” and COPIED the comfunc.c file into comfunc.h. The subsequent compile failed with the following error messages: exit status 1, Error compiling for board Arduino Uno.
I then erased the comfunc.c file, leaving the comfunc.h file. This time the compile failed stating that the comfunc function was undefined. I then added the function definition to the comhdr.h file and the sketch compiled without error.
I have the following questions:
Q1: The procedure that worked included the code for the function in a “.h” file. In my experience with other environments, code that is included with a #include statement generally is placed in a file called xxx.c, or xxx.cpp, not xxx.h. Is this the correct way to include code in an external file in the Arduino IDE, or is there a better way?
Q2: Along the same line as Q1: why did the compiler fail to find the file named comfunc.c, but it had no problem finding comfunc.h?
Q3: Is there a way to put both the definitions file and the code file into a single library subdirectory?
Q4: Why did the compiler fail with exit code 1 when the library directory contained both comfunc.c and comfunc.h files, but does not fail after I erased the “.c” file?
Q5: The Arduino compiler does not require me to predefine the functions in an Arduino program. I have found this to be quite convenient, as other compilers require pre-definition. However, when I include a function using #include, I am forced to predefine the function. Is there an explanation for this?