-4

e.g.

const char* my_func_string = "int func(){"
                       " return 1; }";   //is there a way to do it automatically?
int func(){ 
    return 1;
}

func could be of multiple lines. And I want my_func_string to capture the change whenever I change func. It'd be better if it's captured at compile time because the executables may not find the source code

Jarod42
  • 203,559
  • 14
  • 181
  • 302
M. Wang
  • 13
  • 1
  • It's unclear whether you want to see a listing of a function you've previously written and compiled, or whether you want to execute arbitrary code in a string. Both are difficult. – Robert Harvey Jan 31 '20 at 16:14
  • In C++, there is [`std::embed`'s proposal](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1040r0.html) which might help. – Jarod42 Jan 31 '20 at 16:18
  • Or you can run an external program to parse all the function definitions and put them in the respective variables in an additional file before compiling. Why would you need this feature? – Lukas-T Jan 31 '20 at 16:21
  • @Jarod42 - it appears that the `std::embed` proposal is just for embedding static resources, not about embedding a compiler. – Steve Friedl Jan 31 '20 at 16:32
  • https://stackoverflow.com/questions/42235175/how-do-i-add-contents-of-text-file-as-a-section-in-an-elf-file – Marco Bonelli Jan 31 '20 at 16:44
  • @SteveFriedl: I meant: `auto my_func_string = std::embed("func.cpp");`. it requires indeed to split code in different files. – Jarod42 Jan 31 '20 at 17:11

2 Answers2

2

The best option is writing an external script or code generator that preprocesses your code.

But, if you want a hack, use stringification:

#include <stdio.h>

#define xstr(s) str(s)
#define str(s) #s

#define MYFUNC int myfunc() { return 1; }

char * myfunc_string = xstr(MYFUNC);
MYFUNC

int main()
{
    printf("%s\n%d\n", myfunc_string, myfunc());
    return 0;
}

Prints:

int myfunc() { return 1; }
1

This way you only have to write the function once, inside the #define.

Acorn
  • 24,970
  • 5
  • 40
  • 69
2

Sure, there's "a way", but it's not purely in C. Going back a few decades you can do things like:

$ cat a.c.m4 
define(func,
``int func(void) {
        return 1;
};'')dnl

char *my_func_string = "func";
func
$ m4 a.c.m4 

char *my_func_string = "int func(void) {
        return 1;
};";
int func(void) {
        return 1;
};
William Pursell
  • 204,365
  • 48
  • 270
  • 300