objective-cxcodeobjective-c++swift4.2

How to fix ''Expected ';' after top level declarator" and "Unknown type name 'class'?


I use cocoa to import TUIKit which is a imSDK demo written in objective-c by Tencent into my blank swift app. I get the error: Expected ';' after top level declarator and Unknown type name 'class'; did you mean 'Class'?

The file whith the error is wav.h and there is wav.mm file. Here is the code:

File wav.h

#ifndef WAV_H
#define WAV_H
#include <stdio.h>
class WavWriter {
public:
    WavWriter(const char *filename, int sampleRate, int bitsPerSample, int channels);
    ~WavWriter();
    void writeData(const unsigned char* data, int length);
private:
    void writeString(const char *str);
    void writeInt32(int value);
    void writeInt16(int value);
    void writeHeader(int length);
    FILE *wav;
    int dataLength;
    int sampleRate;
    int bitsPerSample;
    int channels;
};
#endif

The error is on the line "class WavWriter".

The wav.mm file

#import <UIKit/UIKit.h>
#include "wav.h"
void WavWriter::writeString(const char *str) {

    fputc(str[0], wav);
    fputc(str[1], wav);
    fputc(str[2], wav);
    fputc(str[3], wav);
}

....

I searched for two days and couldn't find the answer. Any help? Thanks.


Solution

  • Your wav.h filer is being included in a compilation unit that is not a .mm file (which means "compile as Objective-C++" i.e. either a .m or a .c file.

    You need to enclose the class definition with

    #if defined __cplusplus
    
    // the C++ defs
    
    #endif
    

    The lines between the #ifdef ... #endif will be ignored unless the file being compiled is C++ or Objective-C++.

    If you have straight Objective-C files that need to know the type exists, you can use a typedef to void* or to make it an incomplete struct type

    #if defined __cplusplus
    
    // the C++ defs
    
    class WavWriter {
    // ...
    };
    
    #else
    
    typedef struct WavWriter WavWriter; // Sets up incomplete type for C code
    
    #endif
    
    @interface Foo
    
    @private
        WavWriter* writer; // In C++ a pointer to your class, in C a pointer to an opaque type.