I have a C code block in my org-mode document like the following:
#+begin_src C :exports both
#include "my_header.h"
int main(void)
{
function_from_my_header();
return 0;
}
#+end_src
When I have point inside the code block and C-c C-c
to compile + generate results, I get the following error.
/var/folders/bc/2wq0dn651ys844kp5cz459mc0000gn/T/babel-SktA20/C-src-RnWgKS.c:8:10: fatal error: 'my_header.h' file not found
#include "my_header.h"
^~~~~~~~~~~~~
1 error generated.
zsh:1: permission denied: /var/folders/bc/2wq0dn651ys844kp5cz459mc0000gn/T/babel-SktA20/C-bin-DWq2ho
How do I get org-mode to recognize the header file (which is contained in the same directory as the org file?
It is worth noting: everything has worked fine so far if I don't have (custom) headers (e.g., includes for stdio.h
etc. work fine). It is also worth noting that if I save the source code block to a file and compile using gcc, then the file compiles fine. Ergo, it seems the missing piece is determining how to get org-mode to recognize my_header.h
, which lies in the same directory as the org file itself.
Edit: Solved
I did as NickD suggested but still got an error. To be precise, I have the three files
my_header.c
#include <stdio.h>
#include "my_header.h"
void my_function(void)
{
printf("I can C clearly now.\n");
}
my_header.h
(contains only the prototype formy_function
.my_test.c
#include "my_header.h"
int main(void)
{
my_function();
return 0;
}
When I compile and link from the command line (from within the directory in which these files reside), I run:
gcc my_test.c my_header.c -o my_test && ./my_test
Everything works perfectly.
Now, if I run the following code block from within an org-mode document (residing in the same directory):
#+begin_src C :flags -I .
#include "my_header.h"
int main(void)
{
my_function();
return 0;
}
#+end_src
I get the following error message from the compiler:
Undefined symbols for architecture x86_64:
"_my_function", referenced from:
_main in C-src-fboHG7-40f2c1.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
zsh:1: no such file or directory: /var/folders/bc/2wq0dn651ys844kp5cz459mc0000gn/T/babel-SktA20/C-bin-9wLHvS
The fix (in addition to setting :flags -I.
was to also set :includes my_header.c
The following works perfectly for me when I C-c C-c
in org:
#+begin_src C :flags -I . :includes my_header.c
int main(void)
{
my_function();
return 0;
}
#+end_src
Question summary
How do I get org-mode to recognize the header file (which is contained in the same directory as the org file?
You don't. You point it to the source file corresponding to the header (i.e., my_header.c
) by include
-ing my_header.c
.
Why is this the expected behaviour? My understanding is that this flag creates an #include "my_header.c"
line in the temporary .c
file, and that this is not standard practice when writing C code (one usually includes the .h
file).