Сделайте заголовочный файл, скомпилируйте их и запустите в C - PullRequest
0 голосов
/ 03 апреля 2020

У меня есть задача. Я создал восемь функций, и эти функции работают отлично. У меня проблема с 4. step

В инструкции у меня 4 шага 1. Мне нужно создать заголовочный файл, в который я должен поместить объявление всей функции: (отредактировано) Имя заголовочного файла: textFun c .h


#define _RNM_HPP

int _strlen (char *tab);

int writeText(FILE *wp, char text[]);
int readText(FILE *wp, char text[], int max);
int copyText(char skad[],char dokad[],int max);

int allSigns(char text[]);
int notWhiteSigns(char text[]);
int words(char text[]);
int lines(char text[]);

#endif
Затем я должен создать textFun c. c, в котором у меня есть определения этих функций. (Вам не нужно читать всю эту программу целиком).
#include <stdio.h>
#include <stdlib.h>

int _strlen (char *tab)
{
    int i;
    for (i = 0; tab[i] != '\0'; ++i);    
    return i;
}

int writeText(FILE *wp, char text[])
{
    int len = _strlen(text);
    for (int i = 0; i < len; i++) {
       fputc (text[i], wp);
    }
    return _strlen(text);
}

int readText(FILE *wp, char text[], int max)
{
    int length = _strlen(text);
    int c, i;
    max = 1000;
    while( (c = fgetc(wp)) != EOF && i <= max )
    {
        fputc (text[i], wp);
        i++;
    }
    text[i+1] = '\0';
    if (i < max)
        printf("Array is too big.");
    return _strlen(text);
}

int copyText(char skad[],char dokad[],int max)
{
    if (_strlen(skad) <= max)
    {
        int i;
        for (i = 0; skad[i] != '\0'; ++i)
        {
            dokad[i] = skad[i];
        }
        dokad[i] = '\0';
    }
    return _strlen(dokad);
}

int allSigns(char text[])
{

    int i;
    for (i = 0; text[i] != '\0'; ++i);    
    return i;
}

int notWhiteSigns(char text[])
{
    int sum = 0;
    for (int i = 0; text[i] != '\0'; ++i)
    {
        if ((text[i] != ' ') && (text[i] != '\n') && (text[i] != '\t')  && (text[i] != '\v'))
            sum++;
    }
    return sum;
}

int words(char text[])
{
    int i;
    int sum = 0;
    for (int i = 1; text[i] != '\0'; ++i)
    {
        if (text[i] == ' ' && text[i-1] != ' ' && (text[i] != '\n') && (text[i] != '\t') && (text[i] != '\v') && (text[i-1] != '\n') && (text[i-1] != '\t') && (text[i-1] != '\v')) 
            sum++;
    }
    if (text[i-1] != ' ');
        sum++;
    return sum;
}

int lines(char text[])
{
    int i;
    int sum = 1;
    for (int i = 0; text[i] != '\0'; ++i)
    {
        if (text[i] == '\n')
            sum++;
    }
    return sum;
}


int main (int argc, char *argv[])
{

    char sentence[] = "C is \n a \n programming \t language";

    printf("Show array: %s \n", sentence);

    printf("All signs: %i\n not white signs: %i\n words: %i\n lines: %i\n", allSigns(sentence), notWhiteSigns(sentence), words(sentence), lines(sentence));


    return 0;
}

Затем я должен создать программу с основной функцией mainProgram. c

#include <stdio.h>
#include <stdlib.h>
#include "funTabTekst.h"

int main (int argc, char *argv[])
{

    char sentence[] = "C is \n a \n programming \t language";

    printf("Show array: %s \n", sentence);

    printf("All signs: %i\n not white signs: %i\n words: %i\n lines: %i\n", allSigns(sentence), notWhiteSigns(sentence), words(sentence), lines(sentence));


    return 0;
}
Затем они сказали, что «скомпилируйте каждый исходный файл (с расширением. c) и затем свяжите их вместе, например»
gcc -o mainProgram.x mainProgram.o textFunc.o

У меня проблема с 4. step. Я не могу скомпилировать исходный файл. Я пытаюсь

gcc -o textFunc.o textFunc.c

Я получаю ошибку

/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status

У меня нет функции main, поэтому я добавляю их в textFun c. c

int main()
{
    return 0;
}

компиляция go без ошибок, у меня есть textFun c .o, но я всегда должен ставить основную функцию в каждой программе?

Хорошо, у меня есть textFun c .o теперь мне нужно mainProgram.o

, поэтому я пытаюсь g cc -o mainProgram.o mainProgram. c, но получаю ошибку

gcc -o  mainProgram.o mainProgram.c 
mainProgram.c: In function ‘main’:
mainProgram.c:12:86: warning: passing argument 1 of ‘allSigns’ makes integer from pointer without a cast [-Wint-conversion]
 igns: %i\n not white signs: %i\n words: %i\n lines: %i\n", allSigns(sentence), notWhiteSigns(sentence), words(sentence), lines(sentence));
                                                                     ^~~~~~~~
In file included from mainProgram.c:3:0:
textFunc.h:8:5: note: expected ‘char’ but argument is of type ‘char *’
 int allSigns(char);
     ^~~~~~~~
mainProgram.c:12:111: warning: passing argument 1 of ‘notWhiteSigns’ makes integer from pointer without a cast [-Wint-conversion]
 s: %i\n words: %i\n lines: %i\n", allSigns(sentence), notWhiteSigns(sentence), words(sentence), lines(sentence));
                                                                     ^~~~~~~~
In file included from mainProgram.c:3:0:
textFunc.h:9:5: note: expected ‘char’ but argument is of type ‘char *’
 int notWhiteSigns(char);
     ^~~~~~~~~~~~~
mainProgram.c:12:128: warning: passing argument 1 of ‘words’ makes integer from pointer without a cast [-Wint-conversion]
 \n lines: %i\n", allSigns(sentence), notWhiteSigns(sentence), words(sentence), lines(sentence));
                                                                     ^~~~~~~~
In file included from mainProgram.c:3:0:
textFunc.h:10:5: note: expected ‘char’ but argument is of type ‘char *’
 int words(char);
     ^~~~~
mainProgram.c:12:145: warning: passing argument 1 of ‘lines’ makes integer from pointer without a cast [-Wint-conversion]
 allSigns(sentence), notWhiteSigns(sentence), words(sentence), lines(sentence));
                                                                     ^~~~~~~~
In file included from mainProgram.c:3:0:
textFunc.h:11:5: note: expected ‘char’ but argument is of type ‘char *’
 int lines(char);
     ^~~~~
/tmp/cc2xAejC.o: In function `main':
mainProgram.c:(.text+0x83): undefined reference to `lines'
mainProgram.c:(.text+0x94): undefined reference to `words'
mainProgram.c:(.text+0xa5): undefined reference to `notWhiteSigns'
mainProgram.c:(.text+0xb5): undefined reference to `allSigns'
collect2: error: ld returned 1 exit status

Edit2

Я пытаюсь написать это на моем терминале gcc mainProgram.c textFunc.c -o my_program Я получаю сообщение об ошибке

mainProgram.c: In function ‘main’:
mainProgram.c:12:77: warning: implicit declaration of function ‘allSigns’ [-Wimplicit-function-declaration]
 tf("All signs: %i\n not white signs: %i\n words: %i\n lines: %i\n", allSigns(sentence), notWhiteSigns(sentence), words(sentence), lines(sentence));
                                                                     ^~~~~~~~
mainProgram.c:12:97: warning: implicit declaration of function ‘notWhiteSigns’ [-Wimplicit-function-declaration]
 not white signs: %i\n words: %i\n lines: %i\n", allSigns(sentence), notWhiteSigns(sentence), words(sentence), lines(sentence));
                                                                     ^~~~~~~~~~~~~
mainProgram.c:12:122: warning: implicit declaration of function ‘words’ [-Wimplicit-function-declaration]
 ds: %i\n lines: %i\n", allSigns(sentence), notWhiteSigns(sentence), words(sentence), lines(sentence));
                                                                     ^~~~~
mainProgram.c:12:139: warning: implicit declaration of function ‘lines’; did you mean ‘linie’? [-Wimplicit-function-declaration]
 i\n", allSigns(sentence), notWhiteSigns(sentence), words(sentence), lines(sentence));
                                                                     ^~~~~
                                                                                                                                           linie
/tmp/ccQteDqR.o: In function `main':
textFunc.c:(.text+0x3b6): multiple definition of `main'
/tmp/cc0VFNnF.o:mainProgram.c:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status

Затем я пытаюсь написать другим способом, создавая makefile newMakeFile

my_program: textFunc.o mainProgram.o
    gcc -o my_program textFunc.o mainProgram.o

textFunc.o: textFunc.c
    gcc -o textFunc.o -c textFunc.c 

mainProgram.o: mainProgram.c textFunc.h
    gcc -o mainProgram.o -c mainProgram.c 

и получаю "make" : В 'newMakeFile' нечего делать.

1 Ответ

2 голосов
/ 03 апреля 2020

Самый простой способ скомпилировать ваш код:

gcc mainProgram.c textFunc.c -o my_program

Также необходимо обновить определение функций в textFunc.h так же, как в textFunc.c

#ifndef _RNM_HPP

#define _RNM_HPP

int _strlen (char *tab);

int writeText(FILE *wp, char text[]);
int readText(FILE *wp, char text[], int max);
int copyText(char skad[],char dokad[],int max);

int allSigns(char text[]);
int notWhiteSigns(char text[]);
int words(char text[]);
int lines(char text[]);

#endif

Если вы хотите сначала скомпилировать в file.o. Смотрите простой Makefile ниже:

my_program: textFunc.o mainProgram.o
    gcc -o my_program textFunc.o mainProgram.o

textFunc.o: textFunc.c
    gcc -o textFunc.o -c textFunc.c 

mainProgram.o: mainProgram.c textFunc.h
    gcc -o mainProgram.o -c mainProgram.c 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...