Thread: Convert string to excutable code

  1. #1
    Registered User
    Join Date
    Jan 2017
    Posts
    3

    Convert string to excutable code

    Hi there,

    I have the following variable

    char str[] = "printf("Hello")";

    I want to use the value of str as a part of the program code.

    How to do that?

    In JavaScript there is a function called Eval. Is there any equivalent of it in C?
    Last edited by shb27; 01-06-2017 at 06:41 AM.

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,728
    No, there's no such equivalent in C. You need to parse the string manually, either by means of strtok() or by purely your own code.
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    4,509
    As GReaper says, there is no way to do this using standard C. A quick search however yielded potentially interesting results that may be of use:

    See first and third answers here: Convert string to code at run time c++ - Stack Overflow
    More info: https://web.stanford.edu/~engler/tickc.pdf

  4. #4
    Registered User
    Join Date
    Jan 2017
    Posts
    3
    mmm Is there a way to include .c file within main.c? like include function in php?

  5. #5
    Registered User
    Join Date
    Jun 2015
    Posts
    1,643
    Another (experimental) gnu possibility: https://gcc.gnu.org/onlinedocs/jit/

  6. #6
    Registered User
    Join Date
    Jun 2011
    Posts
    4,509
    You can compile a separate .c file and #include its associated header in your main source file - but you can't include "live" code in this way.

    Perhaps if you tell us exactly what you're trying to accomplish, we can offer alternative suggestions.

  7. #7
    Registered User
    Join Date
    Jan 2017
    Posts
    3
    I managed to include a header and everything seems OK so far.
    Actually I'm trying to make a very simple programming language with c for learning purposes.
    Thanks for your help.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 09-19-2012, 01:58 PM
  2. Replies: 40
    Last Post: 06-03-2010, 12:45 PM
  3. Replies: 5
    Last Post: 05-09-2010, 10:58 AM
  4. convert char** (c string array) to std::string[]
    By umen242 in forum C++ Programming
    Replies: 2
    Last Post: 11-11-2008, 05:52 AM
  5. Replies: 14
    Last Post: 04-01-2008, 02:23 AM

Tags for this Thread