Emscripten Compiler Frontend (emcc)

The Emscripten Compiler Frontend (emcc) is used to call the Emscripten compiler from the command line. It is effectively a drop-in replacement for a standard compiler likegcc orclang.

Command line syntax

emcc[options]file...

(Note that you will need./emcc if you want to run emcc from your current directory.)

The input file(s) can be either source code files thatClang can handle (C orC++), object files (produced byemcc -c), or LLVM assembly files.

Arguments

Mostclang options will work, as willgcc options, for example:

# Display this informationemcc--help# Display compiler version informationemcc--version

To see the full list ofClang options supported on the version ofClang used by Emscripten, runclang--help.

Options that are modified or new inemcc are listed below:

-O0

[compile+link]No optimizations (default). This is the recommended setting for starting to port a project, as it includes various assertions.

This and other optimization settings are meaningful both during compile andduring link. During compile it affects LLVM optimizations, and during link itaffects final optimization of the code in Binaryen as well as optimization ofthe JS. (For fast incremental builds-O0 is best, while for release youshould link with something higher.)

-O1

[compile+link]Simple optimizations. During the compile step these include LLVM-O1 optimizations. During the link step this omits various runtime assertions in JS that-O0 would include.

-O2

[compile+link]Like-O1, but enables more optimizations. During link this will also enable various JavaScript optimizations.

Note

These JavaScript optimizations can reduce code size by removing things that the compiler does not see being used, in particular, parts of the runtime may be stripped if they are not exported on theModule object. The compiler is aware of code in–pre-js and–post-js, so you can safely use the runtime from there. Alternatively, you can useEXPORTED_RUNTIME_METHODS, seesrc/settings.js.

-O3

[compile+link]Like-O2, but with additional optimizations that may take longer to run and may increase code size.

Note

This is a good setting for a release build.

-Og

[compile+link]Like-O1, with an additional flag to extend the liveness of variables for improved debugging.In future versions, additional optimizations might also be disabled.

-Os

[compile+link]Like-O3, but focuses more on code size (and may make tradeoffs with speed). This can affect both Wasm and JavaScript.

-Oz

[compile+link]Like-Os, but reduces code size even further, and may take longer to run. This can affect both Wasm and JavaScript.

Note

For more tips on optimizing your code, seeOptimizing Code.

-sOPTION[=VALUE]

[different OPTIONs affect at different stages, most at link time]Emscripten build options. For the available options, seesrc/settings.js.

Note

If no value is specified it will default to1.

Note

It is possible, with boolean options, to use theNO_ prefix to reverse their meaning. For example,-sEXIT_RUNTIME=0 is the same as-sNO_EXIT_RUNTIME=1 and vice versa. This is not recommended in most cases.

Note

Lists can be specified as comma separated strings:

-sEXPORTED_FUNCTIONS=foo,bar

Note

We also support older list formats that involve more quoting. Lists can be specified with or without quotes around each element and with or without brackets around the list. For example, all the following are equivalent:

-sEXPORTED_FUNCTIONS="foo","bar"-sEXPORTED_FUNCTIONS=["foo","bar"]-sEXPORTED_FUNCTIONS=[foo,bar]

Note

For lists that include brackets or quote, you need quotation marks (”) around the list in most shells (to avoid errors being raised). Two examples are shown below:

-sEXPORTED_FUNCTIONS="['liblib.so']"-s"EXPORTED_FUNCTIONS=['liblib.so']"

You can also specify that the value of an option will be read from a file. For example, the following will setEXPORTED_FUNCTIONS based on the contents of the file atpath/to/file.

-sEXPORTED_FUNCTIONS=@/path/to/file

Note

  • In this case the file should contain a list of symbols, one per line. For legacy use cases JSON-formatted files are also supported: e.g.["_func1","func2"].

  • The specified file path must be absolute, not relative.

  • The file may contain comments where the first character of the line is'#'.

Note

Options can be specified as a single argument with or without a spacebetween the-s and option name. e.g.-sFOO or-sFOO.It’shighly recommended you use the notation without space.

-g

[compile+link]Preserve debug information.

  • When compiling to object files, this is the same as inClang andgcc, itadds DWARF debug information to the object files.

  • When linking, this is equivalent to-g3.

-gseparate-dwarf[=FILENAME]

[same as -g3 if passed at compile time, otherwise applies at link]Preserve debug information, but in a separate file on the side. This is thesame as-g, but the main file will contain no debug info. Instead, debuginfo will be present in a file on the side, inFILENAME if provided,otherwise the same as the Wasm file but with suffix.debug.wasm. Whilethe main file contains no debug info, it does contain a URL to where thedebug file is, so that devtools can find it. You can use-sSEPARATE_DWARF_URL=URL to customize that location (this is useful ifyou want to host it on a different server, for example).

-gsplit-dwarf

Enable debug fission, which creates split DWARF object files alongside thewasm object files. This option must be used together with-c.

-gsource-map[=inline]

[compile+link][same as -g3 if passed at compile time, otherwise applies at link]Generate a source map using LLVM debug information (which mustbe present in object files, i.e., they should have been compiled with-gor-gsource-map).

When this option is provided, the.wasm file is updated to have asourceMappingURL section. The resulting URL will have format:<base-url> +<wasm-file-name> +.map.<base-url> defaultsto being empty (which means the source map is served from the same directoryas the Wasm file). It can be changed using–source-map-base.

Path substitution can be applied to the referenced sources using the-sSOURCE_MAP_PREFIXES (link).Ifinline is specified, the sources content is embedded in the source map(in this case you don’t need path substitution, but it comes with the cost ofhaving a large source map file).

-g<level>

[compile+link]If used at compile time, adds progressively more DWARF information to the object file,according to the underlying behavior of clang.If used at link time, controls the level of debuggability overall. Each level builds on the previous one:

  • -g0: Make no effort to keep code debuggable.

  • -g1: Preserve whitespace in JavaScript.

  • -g2: Also preserve function names in compiled code (via the wasm name section).

  • -g3: Also keep LLVM debug info (DWARF) if there is any in the object files (this is the same as-g).

--profiling

[link]Make the output suitable for profiling. This means including function names in the wasm and JS output, andpreserving whitespace in the JS output. It does not affect optimizations (to ensure that performance profilesreflect production builds). Currenly this is the same as-g2.

--profiling-funcs

[link]Preserve wasm function names as in--profiling, but otherwise minify whitespace and names as we normally do in optimized builds. This is useful if you want to look at profiler results based on function names, but donot intend to read the emitted code.

--tracing

[link]Enable theEmscripten Tracing API.

--reproduce=<file.tar>

[compile+link]Write tar file containing inputs and command to reproduce invocation. Whensharing this file be aware that it will any object files, source files andlibraries that that were passed to the compiler.

--emit-symbol-map

[link]Save a map file between function indexes in the Wasm and function names. Bystoring the names on a file on the side, you can avoid shipping the names, andcan still reconstruct meaningful stack traces by translating the indexes backto the names. This is a simpler format than source maps, but less detailedbecause it only describes function names and not source locations.

Note

When used with-sWASM=2, two symbol files are created.[name].js.symbols (with WASM symbols) and[name].wasm.js.symbols (with ASM.js symbols)

--emit-minification-map<file>

[link]In cases where emscripten performs import/export minificiton this option canbe used to output a file that maps minified names back to their originalnames. The format of this file is single line per import/export of the form<minname>:<origname>.

-flto

[compile+link]Enables link-time optimizations (LTO).

--closure0|1|2

[link]Runs theClosure Compiler. Possible values are:

  • 0: No closure compiler (default).

  • 1: Run closure compiler. This greatly reduces the size of the support JavaScript code (everything but the WebAssembly or asm.js). Note that this increases compile time significantly.

  • 2: Run closure compiler onall the emitted code, even onasm.js output inasm.js mode. This can further reduce code size, but does prevent a significant amount ofasm.js optimizations, so it is not recommended unless you want to reduce code size at all costs.

Note

  • Consider using-sMODULARIZE when using closure, as it minifies globals to names that might conflict with others in the global scope.MODULARIZE puts all the output into a function (seesrc/settings.js).

  • Closure will minify the name ofModule itself, by default! UsingMODULARIZE will solve that as well. Another solution is to make sure a global variable calledModule already exists before the closure-compiled code runs, because then it will reuse that variable.

--closure-args=<args>

[link]Pass arguments to theClosure compiler. This is an alternative toEMCC_CLOSURE_ARGS.

For example, one might want to pass an externs file to avoid minifying JS functions defined in--pre-js or--post-js files.To pass to Closure theexterns.js file containing those public APIs that should not be minified, one would add the flag:--closure-args=--externs=path/to/externs.js

--pre-js<file>

[link]Specify a file whose contents are added before the emitted code and optimized together with it. Note that this might not literally be the very first thing in the JS output, for example ifMODULARIZE is used (seesrc/settings.js). If you want that, you can just prepend to the output from emscripten; the benefit of--pre-js is that it optimizes the code with the rest of the emscripten output, which allows better dead code elimination and minification, and it should only be used for that purpose. In particular,--pre-js code should not alter the main output from emscripten in ways that could confuse the optimizer, such as using--pre-js +--post-js to put all the output in an inner function scope (seeMODULARIZE for that).

–pre-js (but not–post-js) is also useful for specifying things on theModule object, as it appears before the JS looks atModule (for example, you can defineModule['print'] there).

--post-js<file>

[link]Like--pre-js, but emits a fileafter the emitted code.

--extern-pre-js<file>

[link]Specify a file whose contents are prepended to the JavaScript output. Thisfile is prepended to the final JavaScript output,after all otherwork has been done, including optimization, optionalMODULARIZE-ation,instrumentation likeSAFE_HEAP, etc. This is the same as prependingthis file afteremcc finishes running, and is just a convenientway to do that. (For comparison,--pre-js and--post-js optimize thecode together with everything else, keep it in the same scope if runningMODULARIZE, etc.).

--extern-post-js<file>

[link]Like--extern-pre-js, but appends to the end.

--embed-file<file>

[link]Specify a file (with path) to embed inside the generated WebAssembly module.The path is relative to the current directory at compile time. If a directoryis passed here, its entire contents will be embedded.

For example, if the command includes--embed-filedir/file.dat, thendir/file.dat must exist relative to the directory where you runemcc.

Note

Embedding files is generally more efficient thanpreloading as it avoids copying the file data at runtime.

For more information about the--embed-file options, seePackaging Files.

--preload-file<name>

[link]Specify a file to preload before running the compiled code asynchronously. Thepath is relative to the current directory at compile time. If a directory ispassed here, its entire contents will be embedded.

Preloaded files are stored infilename.data, wherefilename.html isthe main file you are compiling to. To run your code, you will need both the.html and the.data.

Note

This option is similar to–embed-file,except that it is only relevant when generating HTML (it uses asynchronousbinaryXHRs), or JavaScript that will be used in a web page.

emcc runstools/file_packagerto do the actual packaging of embedded and preloaded files. You can run thefile packager yourself if you want (seePackaging using the file packager tool).You should then put the output of the file packager in an emcc--pre-js,so that it executes before your main compiled code.

For more information about the--preload-file options, seePackaging Files.

--exclude-file<name>

[link]Files and directories to be excluded from–embed-file and–preload-file. Wildcards (*) are supported.

--use-preload-plugins

[link]Tells the file packager to run preload plugins on the files as they are loaded. This performs tasks like decoding images and audio using the browser’s codecs.

--shell-file<path>

[link]The path name to a skeleton HTML file used when generating HTML output. The shell file used needs to have this token inside it:{{{SCRIPT}}}.

Note

--source-map-base<base-url>

[link]The base URL for the location where WebAssembly source maps will be published. Must be usedwith-gsource-map.

--minify0

[same as -g1 if passed at compile time, otherwise applies at link]Identical to-g1.

--js-transform<cmd>

[link]Specifies a<cmd> to be called on the generated code before it is optimized. This lets you modify the JavaScript, for example adding or removing some code, in a way that those modifications will be optimized together with the generated code.

<cmd> will be called with the file name of the generated code as a parameter. To modify the code, you can read the original data and then append to it or overwrite it with the modified data.

<cmd> is interpreted as a space-separated list of arguments, for example,<cmd> ofpython processor.py will cause a Python script to be run.

--bind

[link]Links against embind library. Deprecated: Use-lembind instead.

--embind-emit-tsd<path>

[link]Generates TypeScript definition file. Deprecated: Use--emit-tsd instead.

--emit-tsd<path>

[link]Generate a TypeScript definition file for the emscripten module. The definitionfile will include exported Wasm functions, runtime exports, and exportedembind bindings (if used). In order to generate bindings from embind, theprogram will be instrumented and run in node.

--ignore-dynamic-linking

[link]Tells the compiler to ignore dynamic linking (the user will need to manually link to the shared libraries later on).

Normallyemcc will simply link in code from the dynamic library as though it were statically linked, which will fail if the same dynamic library is linked more than once. With this option, dynamic linking is ignored, which allows the build system to proceed without errors.

--js-library<lib>

[link]A JavaScript library to use in addition to those in Emscripten’s core libraries (src/library_*).

-v

[general]Turns on verbose output.

This will print the internal sub-commands run by emscripten as well as-vtoClang.

Tip

emcc-v is a useful tool for diagnosing errors. It works with or without other arguments.

--check

[general]Runs Emscripten’s internal sanity checks and reports any issues with thecurrent configuration.

--cache<directory>

[general]Sets the directory to use as the Emscripten cache. The Emscripten cacheis used to store pre-built versions oflibc,libcxx and otherlibraries.

If using this in combination with--clear-cache, be sure to specifythis argument first.

The Emscripten cache defaults toemscripten/cache but can be overriddenusing theEM_CACHE environment variable orCACHE config setting.

--clear-cache

[general]Manually clears the cache of compiled Emscripten system libraries (libc++,libc++abi, libc).

This is normally handled automatically, but if you update LLVM in-place(instead of having a different directory for a new version), the cachingmechanism can get confused. Clearing the cache can fix weird problems relatedto cache incompatibilities, likeClang failing to link with library files.This also clears other cached data. After the cache is cleared, this processwill exit.

By default this will also clear any download ports since the ports directoryis usually within the cache directory.

--use-port=<port>

[compile+link]Use the specified port. If you need to use more than one port you can usethis option multiple times (ex:--use-port=sdl2--use-port=bzip2). A portcan have options separated by:(ex:--use-port=sdl2_image:formats=png,jpg). To use an external port,you provide the path to the port directly(ex:--use-port=/path/to/my_port.py). To get more information about aport, use thehelp option (ex:--use-port=sdl2_image:help).To get the list of available ports, use--show-ports.

--clear-ports

[general]Manually clears the local copies of ports from the Emscripten Ports repos(sdl2, etc.). This also clears the cache, to remove their builds.

You should only need to do this if a problem happens and you want all portsthat you use to be downloaded and built from scratch. After this operation iscomplete, this process will exit.

--show-ports

[general]Shows the list of available projects in the Emscripten Ports repos. After this operation is complete, this process will exit.

-Wwarn-absolute-paths

[compile+link]Enables warnings about the use of absolute paths in-I and-L command line directives. This is used to warn against unintentional use of absolute paths, which is sometimes dangerous when referring to nonportable local system headers.

--proxy-to-worker

[link]Runs the main application code in a worker, proxying events to it and output from it. If emitting HTML, this emits a.html file, and a separate.js file containing the JavaScript to be run in a worker. If emitting JavaScript, the target file name contains the part to be run on the main thread, while a second.js file with suffix “.worker.js” will contain the worker portion.

--emrun

[link]Enables the generated output to be aware of theemrun command line tool. This allowsstdout,stderr andexit(returncode) capture when running the generated application throughemrun. (This enablesEXIT_RUNTIME=1, allowing normal runtime exiting with return code passing.)

--cpuprofiler

[link]Embeds a simple CPU profiler onto the generated page. Use this to perform cursory interactive performance profiling.

--memoryprofiler

[link]Embeds a memory allocation tracker onto the generated page. Use this to profile the application usage of the Emscripten HEAP.

--threadprofiler

[link]Embeds a thread activity profiler onto the generated page. Use this to profile the application usage of pthreads when targeting multithreaded builds (-pthread).

--em-config<path>

[general]Specifies the location of the.emscripten configuration file. If notspecified emscripten will search for.emscripten first in the emscriptendirectory itself, and then in the user’s home directory (~/.emscripten).This can be overridden using theEM_CONFIG environment variable.

--valid-abspath<path>

[compile+link]Note an allowed absolute path, which we should not warn about (absoluteinclude paths normally are warned about, since they may refer to thelocal system headers etc. which we need to avoid when cross-compiling).

-o<target>

[link]When linking an executable, thetarget file name extension defines the output type to be generated:

  • <name>.js : JavaScript (+ separate<name>.wasm file if emitting WebAssembly). (default)

  • <name>.mjs : ES6 JavaScript module (+ separate<name>.wasm file if emitting WebAssembly).

  • <name>.html : HTML + separate JavaScript file (<name>.js; + separate<name>.wasm file if emitting WebAssembly).

  • <name>.wasm : WebAssembly without JavaScript support code (“standalone Wasm”; this enablesSTANDALONE_WASM).

These rules only apply when linking. When compiling to object code (See-cbelow) the name of the output file is irrelevant.

-c

[compile]Tellsemcc to emit an object file which can then be linked with other object files to produce an executable.

--output-eolwindows|linux

[link]Specifies the line ending to generate for the text files that are outputted. If “–output-eol windows” is passed, the final output files will have Windows\r\n line endings in them. With “–output-eol linux”, the final generated files will be written with Unix\n line endings.

--cflags

[other]Prints out the flagsemcc would pass toclang to compile source code to object form. You can use this to invoke clang yourself, and then runemcc on those outputs just for the final linking+conversion to JS.

Environment variables

emcc is affected by several environment variables, as listed below:

  • EMMAKEN_JUST_CONFIGURE [other]

  • EMCC_AUTODEBUG [compile+link]

  • EMCC_CFLAGS [compile+link]

  • EMCC_CORES [general]

  • EMCC_DEBUG [general]

  • EMCC_DEBUG_SAVE [general]

  • EMCC_FORCE_STDLIBS [link]

  • EMCC_ONLY_FORCED_STDLIBS [link]

  • EMCC_LOCAL_PORTS [compile+link]

  • EMCC_STDERR_FILE [general]

  • EMCC_CLOSURE_ARGS [link] arguments to be passed toClosure Compiler

  • EMCC_STRICT [general]

  • EMCC_SKIP_SANITY_CHECK [general]

  • EM_IGNORE_SANITY [general]

  • EM_CONFIG [general]

  • EM_LLVM_ROOT [compile+link]

  • _EMCC_CCACHE [general] Internal setting that is set to 1 by emsdk when integrating with ccache compiler frontend

Search for ‘os.environ’ inemcc.py to see how these are used. The most interesting is possiblyEMCC_DEBUG, which forces the compiler to dump its build and temporary files to a temporary directory where they can be reviewed.