有人成功调用了使用 TCC 的 libtcc 返回 double
的函数吗?
我定义了一个函数来在代码中返回一个double
,并通过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()
却成功?
最佳答案
看看你的 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() 来捕获任何警告和错误。
关于c - TCC 调用返回 double 值的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17273674/