fprintf无法在使用Make编译的C程序中工作

时间:2021-07-27 19:26:33

I have two files with identical C code. I'm compiling one using Make and one using GCC directly (gcc NAME.c -o NAME).

我有两个相同C代码的文件。我正在使用Make和一个直接使用GCC编译一个(gcc NAME.c -o NAME)。

In the GCC-compiled program, all fprintf statements work fine. In the Make-compiled program, only the fprintf statements in the if statements work. The other ones don't print anything. I haven't been able to figure it why.

在GCC编译的程序中,所有fprintf语句都可以正常工作。在Make-compiled程序中,只有if语句中的fprintf语句有效。其他的不打印任何东西。我无法弄清楚原因。

The code is:

代码是:

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

#define BUFFER_SIZE 1000                 

int main(int argc, char ** argv) {       
    fprintf(stdout, "test\n");   
    if (argc != 2) {                     
        fprintf(stderr, "You must have one argument: filename or -h\n");
        return 1;
    }   

    if (strcmp(argv[1], "-h") == 0) {    
        fprintf(stdout, "HELP\n"); /*ADD TEXT HERE*/
    }   
    fprintf(stdout, "got to the end\n"); 
    return 0;                            
}

My makefile:

COMPILER = gcc
CCFLAGS = -ansi -pedantic -Wall

all: wordstat

debug:
    make DEBUG = TRUE

wordstat: wordstat.o
    $(COMPILER) $(CCFLAGS) -o wordstat wordstat.o
wordstat.o: wordstat.c
    $(COMPILER) $(CCFLAGS) wordstat.c

clean:
    rm -f wordstat *.o

The GCC one (run with -h) outputs:

GCC一个(用-h运行)输出:

changed text
HELP
got to the end

The Make one outputs:

Make one输出:

HELP

Any help would be much appreciated.

任何帮助将非常感激。

1 个解决方案

#1


0  

You forgot the -c option in the makefile:

你忘了makefile中的-c选项:

.
.
.    
wordstat.o: wordstat.c  
    $(COMPILER) $(CCFLAGS) -c wordstat.c
                            ↑ - important!

Else this line doesn't generate an object file but an executable elf file (a.out), and thus may lead to unexpected behavior because you recompile that to wordstat ( and it is already compiled).

否则此行不会生成目标文件,而是生成可执行的elf文件(a.out),因此可能会导致意外行为,因为您将其重新编译为wordstat(并且已经编译)。

#1


0  

You forgot the -c option in the makefile:

你忘了makefile中的-c选项:

.
.
.    
wordstat.o: wordstat.c  
    $(COMPILER) $(CCFLAGS) -c wordstat.c
                            ↑ - important!

Else this line doesn't generate an object file but an executable elf file (a.out), and thus may lead to unexpected behavior because you recompile that to wordstat ( and it is already compiled).

否则此行不会生成目标文件,而是生成可执行的elf文件(a.out),因此可能会导致意外行为,因为您将其重新编译为wordstat(并且已经编译)。