我正在学习 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 失败?