1

double有没有人用 TCC 的 libtcc成功调用了一个返回 a的函数?

我定义了一个函数来在我的代码中返回 adouble并通过tcc_add_symbol将它添加到 libtcc 中。当我在 tcc 脚本中调用此函数并获得返回值时,该值为0.000,这不是我所期望的。

编码:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "libtcc.h"

double get_double()
{
return 80.333;
}

int get_int()
{
return 333;
}

char my_program[] =
"int foo()\n"
"{\n"
"    printf(\"Hello World!\\n\");\n"
"    printf(\"double: %.4f\\n\", get_double()); \n"
"    printf(\"int: %d\\n\", get_int()); \n"
"    return 0;\n"
"}\n";

int main(int argc, char **argv)
{
TCCState *s;
typedef int (*func_type)();
func_type func;

s = tcc_new();
if (!s) {
    fprintf(stderr, "Could not create tcc state\n");
    exit(1);
}

tcc_set_lib_path(s, "TCC");

tcc_set_output_type(s, TCC_OUTPUT_MEMORY);

if (tcc_compile_string(s, my_program) == -1)
    return 1;
tcc_add_symbol(s, "get_double", get_double);
tcc_add_symbol(s, "get_int", get_int);

if (tcc_relocate(s, TCC_RELOCATE_AUTO) < 0)
    return 1;

func = (func_type)tcc_get_symbol(s, "foo");
if (!func)
    return 1;

func();
tcc_delete(s);
getchar();
return 0;
}

运行代码的结果:

Hello World!

double: 0.0000

int: 333

为什么get_double()函数返回0.0000,但是get_int()成功了?

4

1 回答 1

1

看看你的 int foo() 片段。你要记住,这个字符串就是整个编译单元,就好像你把它存成一个C文件一样。在这个编译单元中,get_int() 和 get_double() 实际上是未定义的。由于运气好,int 版本可以工作,因为所有未声明的变量和函数都具有 int 类型。这也是 get_double 不起作用的原因,因为同样的规则假定它在 int 函数中。

解决方法很简单。只需在脚本中声明您的函数。使用头文件或类似的东西:

char my_program[] =
"double get_double();\n"
"int get_int();\n"
"int foo()\n"
"{\n"
"    printf(\"Hello World!\\n\");\n"
"    printf(\"double: %.4f\\n\", get_double()); \n"
"    printf(\"int: %d\\n\", get_int()); \n"
"    return 0;\n"
"}\n";

我强烈建议您使用 tcc_set_error_func() 来捕获任何警告和错误。

于 2013-06-25T01:45:49.220 回答