2

所以,我正在尝试制作一个 Pebble 应用程序,当您按下按钮时会生成一个随机字符串。我很确定我的 Pebble 代码是正确的,但我不确定如何处理这个错误:

/sdk2/[long stuff here]/ In function `_sbrk_r':
/home/[more long stuff]: undefined reference to `_sbrk'
collect2: error: ld returned 1 exit status
Waf: Leaving directory `/tmp/tmpX94xY7/build'
Build failed

这是我的代码:

#include <pebble.h>
#include <stdlib.h>
#include <stdio.h>

Window *window;
TextLayer *text_layer;

char* one[] = {"string1", "stringone", "stringuno"};
char* two[] = {"string2", "stringtwo", "stringdos"};
char* three[] = {"string3", "stringthree", "stringtres"};
char* four[] = {"string4", "stringfour", "stringcuatro"};

int length1 = sizeof(one)/sizeof(*one);
int length2 = sizeof(two)/sizeof(*two);
int length3 = sizeof(three)/sizeof(*three);
int length4 = sizeof(four)/sizeof(*four);

char* gen()
{
    char out[256];
    sprintf(out, "%s, and then %s %s %s.", one[rand() % length1], two[rand() % length2], three[rand() % length3], four[rand() % length4]);

    char* result = malloc(strlen(out) + 1);
    strcpy(result, out);
    return result;
}

static void select_click_handler(ClickRecognizerRef recognizer, void *context)
{
    char* stringGen = gen();
    text_layer_set_text(text_layer, stringGen);
    free(stringGen);
}

static void click_config_provider(void *context)
{
    window_single_click_subscribe(BUTTON_ID_SELECT, select_click_handler);
    window_single_click_subscribe(BUTTON_ID_UP, select_click_handler);
    window_single_click_subscribe(BUTTON_ID_DOWN, select_click_handler);
}

static void window_load(Window *window)
{
    Layer *window_layer = window_get_root_layer(window);
    GRect bounds = layer_get_bounds(window_layer);

    text_layer = text_layer_create((GRect) { .origin = { 0, 72 }, .size = { bounds.size.w, bounds.size.h } });
    text_layer_set_text(text_layer, "Press >>>");

    text_layer_set_text_alignment(text_layer, GTextAlignmentCenter);
    layer_add_child(window_layer, text_layer_get_layer(text_layer));
}

static void window_unload(Window *window)
{
    text_layer_destroy(text_layer);
}

void handle_init(void)
{
    window = window_create();
    window_set_click_config_provider(window, click_config_provider);
    window_set_window_handlers(window, (WindowHandlers) {
        .load = window_load,
        .unload = window_unload,
    });
    const bool animated = true;
    window_stack_push(window, animated);    
}

void handle_deinit(void)
{
      text_layer_destroy(text_layer);
      window_destroy(window);
}

int main(void)
{
    handle_init();
    app_event_loop();
    handle_deinit();
}

我不知道为什么我会收到这个错误。这是一个简单的应用程序,我只有这些小调整。

预先感谢您的帮助!

4

1 回答 1

2

根据这个(旧)常见问题解答,当您尝试使用尚未在 SDK 中实现的 C 标准库函数时会发生该错误。如果您查看API 参考snprintf是可用的,但不是sprintf。你可以用类似的东西代替你sprintfgen电话

snprintf(out, 256, "%s, and then %s %s %s.", one[rand() % length1], two[rand() % length2], three[rand() % length3], four[rand() % length4]);

我刚试过这个,它构建得很好。

out(顺便说一句,声明一个全局静态缓冲区并每次只覆盖它可能是一个更好的主意,而不是不断地动态分配内存。)

于 2014-03-10T06:33:41.230 回答