Nyht
Nyht

Reputation: 11

C++ Struct function in an another header gives "missing type specifier"

I got in my "main.cpp" the following code:

#include "rational.h"

using namespace std;

typedef struct rational {
    long long numerator;
    long long denominator;
} rational_t;

And I have a Header-file namend "rational.h":

#pragma once


rational add(rational  a,rational b)
{
    rational c;
    c.numerator = a.numerator + b.numerator;
    c.denominator = a.denominator + b.denominator;
    return c;
}

I got an Error on Line:

rational add(rational  a,rational b)

It gives me the following Error-Code: Fehler C4430 Fehlender Typspezifizierer - int wird angenommen. Hinweis: "default-int" wird von C++ nicht unterstützt. Translation: Error C4430 Missing Type specifier - int is accepted. "default-int" is not supported by C++.

I think because the function does not detect my struct properly. Can anyone pls help me?

Greetings, Nike

Upvotes: 0

Views: 887

Answers (1)

Andrew Weir
Andrew Weir

Reputation: 41

You haven't pasted your full source code for main.cpp and rational.h, so this makes it a little harder to debug properly. Based only on what you've given:

  1. Your structure was called "rational" but you've used typedef and defined it as a new type, or another way of declaring a "struct rational" called rational_t. Your function should return a rational_t, and accept rational_t for both parameters.

  2. You likely meant to put the struct rational into rational.h, ahead of your function declaration.

It's pretty hard to determine if you want to use C++ or C from this example code too, so I've written it up in C. It'll be a start for you to learn from.

main.c

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

#include "rational.h"

int main() 
{
    rational_t first;
    rational_t second;

    first.numerator = 5;
    first.denominator = 7;

    second.numerator = 3;
    second.denominator = 9;

    rational_t product = add(first, second);
    printf("%lld / %lld\n", product.numerator, product.denominator);

    return 0;
}

rational.h

#ifndef RATIONAL_H_
#define RATIONAL_H_

typedef struct rational {
    long long numerator;
    long long denominator;
} rational_t;

rational add(rational  a,rational b)
{
    rational c;
    c.numerator = a.numerator + b.numerator;
    c.denominator = a.denominator + b.denominator;
    return c;
}

#endif // RATIONAL_H_

Upvotes: 1

Related Questions