1# Copyright 2019 The Bazel Authors. All rights reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15"""Example showing how to create a rule that just compiles C sources.""" 16 17load("@rules_cc//cc:action_names.bzl", "C_COMPILE_ACTION_NAME") 18load("@rules_cc//cc:find_cc_toolchain.bzl", "find_cpp_toolchain", "use_cc_toolchain") 19 20MyCCompileInfo = provider(doc = "", fields = ["object"]) 21 22DISABLED_FEATURES = [ 23 "module_maps", # # copybara-comment-this-out-please 24] 25 26def _my_c_compile_impl(ctx): 27 cc_toolchain = find_cpp_toolchain(ctx) 28 source_file = ctx.file.src 29 output_file = ctx.actions.declare_file(ctx.label.name + ".o") 30 feature_configuration = cc_common.configure_features( 31 ctx = ctx, 32 cc_toolchain = cc_toolchain, 33 requested_features = ctx.features, 34 unsupported_features = DISABLED_FEATURES + ctx.disabled_features, 35 ) 36 c_compiler_path = cc_common.get_tool_for_action( 37 feature_configuration = feature_configuration, 38 action_name = C_COMPILE_ACTION_NAME, 39 ) 40 c_compile_variables = cc_common.create_compile_variables( 41 feature_configuration = feature_configuration, 42 cc_toolchain = cc_toolchain, 43 user_compile_flags = ctx.fragments.cpp.copts + ctx.fragments.cpp.conlyopts, 44 source_file = source_file.path, 45 output_file = output_file.path, 46 ) 47 command_line = cc_common.get_memory_inefficient_command_line( 48 feature_configuration = feature_configuration, 49 action_name = C_COMPILE_ACTION_NAME, 50 variables = c_compile_variables, 51 ) 52 env = cc_common.get_environment_variables( 53 feature_configuration = feature_configuration, 54 action_name = C_COMPILE_ACTION_NAME, 55 variables = c_compile_variables, 56 ) 57 58 ctx.actions.run( 59 executable = c_compiler_path, 60 arguments = command_line, 61 env = env, 62 inputs = depset( 63 [source_file], 64 transitive = [cc_toolchain.all_files], 65 ), 66 outputs = [output_file], 67 ) 68 return [ 69 DefaultInfo(files = depset([output_file])), 70 MyCCompileInfo(object = output_file), 71 ] 72 73my_c_compile = rule( 74 implementation = _my_c_compile_impl, 75 attrs = { 76 "src": attr.label(mandatory = True, allow_single_file = True), 77 "_cc_toolchain": attr.label(default = Label("@rules_cc//cc:current_cc_toolchain")), 78 }, 79 toolchains = use_cc_toolchain(), 80 fragments = ["cpp"], 81) 82