[英]fix ms compiler c code to compile in gcc
您好,在15年前閱讀一本c和一本c ++書籍大約一半后,我對c / c ++語言有了一些非常基本的了解。
大約在那個時候,在1998年9月,我買了一本書“ 3D游戲編程的妖術,用c編寫自己的高速3d多邊形視頻游戲”。 出版商-Waite,作家-Andre LaMothe。 它的位置很容易,因此您不必以c為前提就可以學習本書。 那時我真的很想學習它,但是卻參與了其他事情,並被其他項目分散了注意力。 在那個時候,我發現了其他幾種語言。 我嘗試過perl,真的很喜歡它。 我很快就了解了它的基礎知識,並用3個月+ 3個月的時間編寫了我的第一個大型項目,並用perl進行了修復和微調。 從那時起,我開始學習更多知識並提高perl,因此沒有時間來學習c。
學習游戲和圖形編程的願望從未離開過我,因此,我決定回到那本游戲編程書中。 我知道,您現在可以學習OpenGL或WebGL,但是在我看來,這本書有很多低級的概念,如果您不學習,將不會像可能的那樣成為游戲編程的好手,但是,本書要求您具有MS C / C ++ 7.0編譯器。 從那時起,我已經轉移到linux(5年前)了,不想回到Windows。 另外,無論我學到什么,我都希望它是跨平台的,所以我寧願弄清楚如何修改本書的代碼以在gcc中進行編譯,然后在wine或Windows虛擬機中安裝MS C / C ++ 7.0編譯器。
在書里:
//input driven event loops
//includes
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void main(void){
int done=0,
number,
num_tries=0,
guess;
//removed far from the unsigned line, because compiler complains:
//error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
// unsigned int far *clock = (unsigned int far *)0x0000046CL; //clock pointer
unsigned int *clock = (unsigned int *)0x0000046CL; //clock pointer
//section 1
printf("\nI'm thinking of a number from 1-100.");
printf("\nTry and guess it!\n");
srand(*clock);
number = 1 + rand() % 100;
printf("test");
}
本書中的代碼同上,只是注釋的無符號行是原始代碼,但未注釋的行被修改了。 更改無符號行后,它將使用gcc file_name.c進行編譯,但是當編譯后的二進制文件的執行到達srand行時,該程序將因分段錯誤而退出。 我想,“遠”事與ms編譯器有關,也許整行都與獲取時鍾指針有關。 關於如何解決該問題的任何建議?
好的,我知道時鍾指針行在現代編程中是無用的,我應該使用time.h,因此我將時鍾指針更改為time()函數。 另外,我建議將return和int添加到主函數中。 這是新代碼:
//input driven event loops
//includes
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int main(void){
int done=0,
number,
num_tries=0,
guess;
//section 1
printf("\nI'm thinking of a number from 1-100.");
printf("\nTry and guess it!\n");
srand(time(NULL));
number = 1 + rand() % 100;
return(0);
}
現在工作正常,沒有分段錯誤。 謝謝。
far
是非標准的C關鍵字。 除非您確定需要它,否則請不要理會它。
從代碼來看,這是一個簡單的猜測數字游戲, clock
應該為隨機生成器提供種子。 同樣, 0x0000046CL
是一些導致分段錯誤的不可移植代碼。
為了簡單起見,請使用當前時間作為種子。
srand(time(0))
好吧,這是從時鍾獲取時間的不贊成使用的方法。
采用
srand(time(NULL)); //#include <time.h>
它會給您當前時間,我想您的代碼有一些安全問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.