glideapps / quicktype

Generate types and converters from JSON, Schema, and GraphQL
https://app.quicktype.io
Apache License 2.0
11.76k stars 1.04k forks source link

[FEATURE]: cJSON - generate source/header pairs #2617

Open thives opened 2 weeks ago

thives commented 2 weeks ago

Add a way to generate source files instead of only header files.

Context (Input, Language)

Input Format: json schema

Output Language: C (cJSON)

Description

Header only makes it more complicated and limited in how to use the generated code. C operates with compilation units that end up as object files that are then linked together. Having implementations inside a header file may lead to linkage issues when the same symbols appear in multiple object files.

In general C is typically written with matching .c and .h pairs, with all the definitions in the header file, and all the implementations in the source file.

We will improve the quality of the generated code by separating into separate source files and header files:

Current Behaviour / Output

Currently Quicktype generates one or more header files containing both definitions and implementations.

Proposed Behaviour / Output

Quicktype should generate header files containing only definitions, and source files containing only implementations.

Solution

The code generator already generate definitions first then proceeds generating implementations. The easiest solution is to close the header file and then open a source file after the definitions have been emitted and before emitting implementations. The source files and header files are usually named the same with different extensions. We can use this and simply replace the .h with .c when creating the corresponding source files.

To avoid changing existing behavior and breaking projects out there I propose to add a command line switch to turn on the generation of source files, leaving the default behavior unchanged.

I have implemented this in a fork and will provide a PR.

Alternatives

The current alternative is to only include the generated header in one source file per project to avoid linkage issues.

Another option is to post process the generated code with external tools, but that is a lot more work and very fragile hack.