在unix上运行C程序而不是在命令行中运行

时间:2015-10-09 02:21:51

标签: c runnable compiled

它可能是我的代码,但我可以通过命令行编译和运行该程序。在Windows中,exe文件也是可运行的。但是,我无法在任何unix系统(ubuntu或osx)上运行终端外的编译代码。我对C很新,所以任何帮助都会受到赞赏。谢谢!

澄清:

在Ubuntu中我运行

gcc game.c -o game
./game

然后它完美运行。但是,如果我通过GUI浏览游戏文件并双击它,它就不会做任何事情。 我以前在Windows上会调出一个命令来运行程序,就像从cmd运行它一样。

代码(这是一个简单的猜数游戏):

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int guessed = 0;
int guesses = 0;
int total_guesses = 0;
int games_played = 0;
int range_top = 10;
int generate_random_number()
{
    srand(time(NULL));
    return (rand() % range_top);
}
void take_guess(int num)
{
    int guess;
    printf("what is your guess:  ");
    scanf(" %i",&guess);
    if(guess == num)
    {
        guessed = 1;
    }
    else if(guess>num)
    {
        printf("Your guess was too high,\n");
    }
    else 
    {
        printf("Your guess was too low.\n");
    }

}
void print_stats()
{
        printf("\n\n\nGames Played: %i\nTotal Guesses: %i\nAverage Guesses Per Game: %f\n\n\n\n",games_played,total_guesses,(double)total_guesses/games_played);
        int i = 5;
        while(i>0)
        {
                printf("exiting in %is\n",i);
                i--;
                sleep(1);
        }
}
int main(void)
{
    printf("This is a game in C\n");
    printf("Would you like to play? (y/n): ");
    char play;
    scanf("%c",&play);
    while(play == 'y')
    {
        printf("I am thinking of a number between 0 and %i\n",range_top);
        int num = generate_random_number();
        while(guessed ==0)
        {
            take_guess(num);
            guesses++;
        }
        games_played++;
        total_guesses+=guesses;
        printf("It took you %i guesses to win.\n",guesses);
        printf("Would you like to play again? (y/n): ");
        scanf(" %c",&play);
        guessed = 0;
        guesses = 0;
    }
    print_stats();
}

1 个答案:

答案 0 :(得分:0)

  

但是,如果我通过GUI浏览游戏文件并双击它,它   什么都不做

你怎么知道它没有运行?我打赌它 运行,但由于它不是在任何终端(命令行窗口)的上下文中运行,你只是看不到它的输出。这就是Linux(以及Unix)的工作方式。

Windows区分GUI和命令行应用程序,在后一种情况下会自动带来控制台窗口。不幸的是(幸运的是?),在Unix中并非如此。

如果您想实现Windows行为,您可以:

  1. Create a launcher for your application。这将允许您指定自定义图标等。

  2. 创建一个shell脚本,该脚本将调用teminal及其中的应用程序:

  3. game.sh

    #!/bin/bash
    gnome-terminal -e "./game"
    

    请注意,并非每个人都安装了gnome-temrinal,因此您可能需要调整脚本以支持更多终端模拟器(xtermrxvt,也许konsole KDE用户)。