0

我正在学习 C 并试图确保我的代码是可移植的。为此,我在 Mac(ARM、PPC、Intel)、Linux(ARM、PPC、PA-RISC)和 HP-UX(PA-RISC)上构建。为了确保我有一种简单的方法来输出简单的图形,我使用了 GLUT。

我有以下代码和功能:

GLfloat white[3] = { 1.0, 1.0, 1.0 };
GLfloat red[3] = { 1.0, 0.0, 0.0 };
GLfloat green[3] = { 0.0, 1.0, 0.0 };

void printText(char *text, const GLfloat colour[3], float posX, float posY) {
    glColor3fv (colour);
    glRasterPos2f(posX, posY); //define position on the screen
      
    while(*text){
      glutBitmapCharacter(GLUT_BITMAP_8_BY_13, *text++);
    }
}

void GLprintTextAndInteger (char *text, int value, float colour[3], float posX, float posY) {
    int length = snprintf(NULL, 0, "%s %i", text, value);
    char *stringToPrint = malloc(length + 1);
    snprintf(stringToPrint, length + 1, "%s %i",text,value);
    printText(stringToPrint,colour,posX,posY);
    free(stringToPrint);
}

void GLprintTextAndLong (char *text, long value, float colour[3], float posX, float posY) {
    int length = snprintf(NULL, 0, "%s %ld", text, value);
    char *stringToPrint = malloc(length + 1);
    snprintf(stringToPrint, length + 1, "%s %ld", text, value);
    printText(stringToPrint,colour,posX,posY);
    free(stringToPrint);
}

我称之为如下,例如:

GLprintTextAndInteger("sample text", int whatever, white, -0.98f, 0.1f);
GLprintTextAndLong("sample text", long whatever, white, -0.98f, 0.0f);
printText("some text",white,-0.98f,-0.1f);

当我在 HP-UX 上构建时,同时使用 HP 的编译器和 GCC,当我运行程序时,只有 printText 有效。GLprintTextAndInteger 和 GLprintTextAndLong 什么都不做(或者它们可能工作,但是是黑色的,然后我看不到输出)。代码在所有平台上构建时都没有任何警告。它在 Linux 和 Mac 上运行良好,适用于所有架构。

有什么建议么?

编辑:

在故障排除过程中,我发现如果我更换:

int length = snprintf(NULL, 0, "%s %i", text, value);

int length = 40;

它工作正常。为什么 snprintf 失败?

4

1 回答 1

0

根据手册页snprintf(3s)(参见https://www.unix.com/man-page/hpux/3s/snprintf/):

默认情况下,如果 maxsize 小于格式化的字符数,则返回负值。在 UNIX 2003 标准环境中(请参阅standards(5)),如果 maxsize 足够大,它会返回将写入缓冲区 s 的字节数,不包括终止的空字节。

UNIX 2003 标准仅在 HP-UX 11iv3 (11.31) 上受支持,如果您这样编译:

$ export UNIX_STD=2003
$ make/cc/whatever

这是我用来验证这一点的测试程序:

root@hpvm01:~/t$ cc -o s s.c
root@hpvm01:~/t$ ./s
r=0
root@hpvm01:~/t$ UNIX_STD=2003 cc -o s s.c
root@hpvm01:~/t$ ./s
r=6
root@hpvm01:~/t$ cat s.c
#include <stdio.h>

int main()
{
  int r = snprintf(NULL, 0, "hello\n");

  printf("r=%d\n", r);
}

所以我希望你使用的是 11.31 而不是更早的版本。在这种情况下,snprintf 的开源版本可能会有所帮助:http ://hpux.connect.org.uk/hppd/hpux/Development/Libraries/snprintf-2.2/

于 2021-12-03T13:30:33.753 回答